在python / GAE中声明全局变量的问题 [英] Problem declaring global variable in python/GAE

查看:78
本文介绍了在python / GAE中声明全局变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我试图从UI获取用户名,并查询结果以获取用户的电话簿联系人。但我无法将用户名设置为全局变量以将其用于多个查询。这里是代码,我相信我在做一些语法错误/不正确的用法,请帮助我纠正我的代码。

 #! / usr / bin / env python 

从google.appengine.ext导入wsgiref.handlers
从google.appengine.ext导入db
从google导入webapp
。 appengine.ext.webapp导入模板
导入模型

class showPhoneBook(db.Model):
username = db.StringProperty(required = True)

class MyHandler(webapp.RequestHandler):
user_name =''
def get(self):
p = db.GqlQuery('SELECT * FROM UserDetails WHERE user_name = $ 1',user_name)
#p = UserDetails.gql('WHERE user_name = $ 1',user_name)
result1 = p.fetch(1)
for result1中的itr1:
userId = itr.user_id
q = db.GqlQuery('SELECT * FROM PhoneBook WHERE user_id = 1,userId)
#q = PhoneBook.gql('WHERE user_id = 1,userId)
values = {
'phoneBookValues':q
}
self.request.out.write(
template.render('phonebook.html',values))
def post(self):
global user_name
phoneBookuserID = showPhoneBook(
user_name = self.request.get(
'username'))
self.request.out。 write(user_name)
phonebookuserID.put()
self.redirect('/')

def main():
app = webapp.WSGIApplication([
(r'。*',MyHandler)],debug = True)
wsgiref.handlers.CGIHandler()。run(app)
$ b if if __name__ ==__main__:
main()

这里 UserDetails 电话簿是我的 models.py

中定义的实体类

请帮助我找到错误...或者可能获得更正了如何在通过UI获取用户名后在查询中使用user_name的代码。

解决方案

首先,App Engine的执行模式相当松散 - 这就是为什么它具有很强的可扩展性!当请求到达您的URL时,GAE可以重用已经运行脚本的现有进程,它可以启动运行相同脚本的另一个进程,以更好地平衡整体系统负载;一旦请求被提供,服务的进程可能会停留或不停留,这取决于系统是否有更好的方法来处理进程占用的内存。

因此,您必须以任何一种情况下都能工作的方式进行编码,而不会假定进程将在请求之间停留(并且不假设它也不会)。所以全局变量(绝大多数情况下最好的避免在所有类型的编程中)绝对不是要走的路!



唯一保证的方法是保持请求之间的事情是将它们存储在数据库中;发送cookie到用户的浏览器作为响应中的标题,因此所述浏览器将在下一个请求中发回,也可能是好的(用户可能决定阻止他的浏览器接受和重新发送cookie,但这是用户的决定,你不能做太多的事情)。

一个sesssion的抽象概念可以封装这些选择,让你在更高的层次上编程,许多框架提供某种会话,例如,请参阅 gaeutilities ,除非您已经使用其他一些Web框架提供会话抽象。

您的代码还有许多其他特定问题(例如用户名和<$之间的混淆c $ c> user_name ,全局变量和类变量之间的混淆,以及缺少任何赋值!),但从某种意义上讲,与使用整个概念性问题相比,这些都是次要问题g应用程序引擎中的全局变量! - )


I'm new to python and I'm trying to obtain a username from the UI and query the result to get the phone book contacts of the user. But I am not able to set the user name to be a global variable to use it for multiple queries. Here's the code, I believe I am doing some syntax error/improper usage, please help out in correcting my code.

#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import models

class showPhoneBook(db.Model):
    username = db.StringProperty(required=True)

class MyHandler(webapp.RequestHandler):
    user_name = ''
    def get(self):
        p = db.GqlQuery('SELECT * FROM UserDetails WHERE user_name = $1', user_name)
        #p = UserDetails.gql('WHERE user_name = $1', user_name)
        result1 = p.fetch(1)
        for itr1 in result1:
            userId = itr.user_id
        q = db.GqlQuery('SELECT * FROM PhoneBook WHERE user_id = :1', userId)
        #q = PhoneBook.gql('WHERE user_id = :1', userId)
        values = {
            'phoneBookValues': q
        }
        self.request.out.write(
            template.render('phonebook.html', values))
    def post(self):
        global user_name
        phoneBookuserID = showPhoneBook(
            user_name = self.request.get(
                'username'))
        self.request.out.write(user_name)
        phonebookuserID.put()
        self.redirect('/')

def main():
    app = webapp.WSGIApplication([
        (r'.*',MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()

Here UserDetails and Phonebook are my entity classes defined in my models.py

Please Help me in finding the error...or possibly get a corrected code of how to use user_name in queries after obtaining it from the UI.

解决方案

First and foremost, App Engine's execution model is quite "loose" -- that's why it's so scalable! When a request arrives for your URL, GAE may reuse an existing process that's already running your script, or it may start another process running the same script if that balances overall system load better; once the request is served, the process that served it may stick around or not, depending on whether the system has something better to do with the memory that the process is occupying.

You must therefore code in a way that works in either situation, without assuming that the process will stick around between requests (and without assuming it won't, either). So global variables (most always best avoided in all kinds of programming) are definitely not the way to go!

The only guaranteed way to persist things between requests is to store them in the db; sending a cookie to the user's browser as a header in your response, so said browser will send it back on the next request, is also likely to be OK (the user may decided to block his browser from accepting and resending cookies, but that's the user's decision and you can't really do much about it).

The abstract concept of a "sesssion" can encapsulate these choices and let you program at a higher level and many frameworks offer some kind of session, for example see gaeutilities unless you're already using some other web framework supplying a session abstraction.

There are many other specific issues with your code (such as confusion between username and user_name, confusion between global variables and class variables, and the lack of any assignment to either!), but in a sense these are minor issues compared to the whole conceptual problem of using globals in app engine!-)

这篇关于在python / GAE中声明全局变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆