如何查询GAE数据存储区以呈现模板(新手级) [英] How to query GAE datastore to render a template (newbie level)

查看:167
本文介绍了如何查询GAE数据存储区以呈现模板(新手级)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触编程,我想了解GAE资料储存库的概念。我正在尝试构建一个应用程序,以便轻松撰写合同( http://contractpy.appspot.com ) )。目前,我传递的所有值,我需要从URL提交合同模板,这样:

  self。 redirect('/ your_contract?person =%s& nacionality =%s& profession =%s& maritalStatus =%s& SSN =%s& driverLicense =%s& email =%s& witness =%s& owner =%s& ; contractType =%s& address =%s'%(person_name,user_nacionality,user_profession,user_maritalStatus,user_SSN,user_driverLicense,user_email,
#witness,owner,contractType,address))

但是,这样做只限于一个人(并且在将来,我需要在同一份合同中提供几个人的数据)。



而不是这样做,我想使用GAE数据存储查询来填充模板your_contract.html的变量值。



我知道这是一个简单的问题,但GAE数据存储对我来说是完全不清楚的(我还没有抓住数据存储区的禅,但我理解了一点的SQL),我正在学习OOProgramming。我阅读了这篇文章,我试图关注这个示例(Google guess_booK示例),但它们不足以应付这个大脑。那么,什么是最好的方式来做这个查询,在一个模板中渲染几个人的数据? (类Person在下面的代码中)



我这样想:通过URL一个列表,每个人的数据(例如:驾驶执照号码):

  self.redirect('/ your_contract?driverLicense =%s'%(driverLicenseList))



<

  x = self.request.get('SSN')
contractingParty = db.GqlQuery WHERE SSN IS x)

这是正确的路径吗?



我的原始代码(在执行GAE查询之前)位于:

 # -  *  -  coding:utf-8  -  *  -  
# - * - coding:utf-8 - * -
#!/ usr / bin / env python

#版权所有2007 Google Inc.

#根据Apache许可2.0版(许可)授权;
#您不能使用此文件,除非符合许可证。
#您可以通过以下方式获取许可证的副本:

#http://www.apache.org/licenses/LICENSE-2.0

#除非适用法律要求或以书面形式同意,软件
#根据许可证分发的软件以原样基础分发,
#不包含任何明示或暗示的担保或条件。
#查看许可证管理权限的特定语言和
#许可证下的限制。


import os

import webapp2

import jinja2

jinja_environment = jinja2.Environment(autoescape = True,
loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__ file__),'templates')))

import re

来自google.appengine.ext import db

USER_RE = re.compile(r^ [a-zA-Z0-9_ - ] {3,20} $)
def valid_person(person):
return USER_RE.match(person)

PASS_RE = re.compile(r^。{3,20} $)
def valid_SSN ):
return PASS_RE.match(SSN)

EMAIL_RE = re.compile(r^ [\S] + @ [\S] + \。[\S ] + $)
def valid_email(email):
return EMAIL_RE.match(email)

导入时间

import datetime

def dateToday():
today = datetime.datetime.today()
todayDay = str(today.day)
todayMonth = str(today.month)
monthExt = {'1':'一月','2':'二月','3':'三月','4':'四月','5':'五月','6' ,'7':'July','8':'August','9':'September','10':'October','11':'November','12':' b $ b todayYear = str(today.year)
return(todayDay +'of'+ monthExt [todayMonth] +'of'+ todayYear)

class MainHandler(webapp2.RequestHandler):
def get(self):
template_values = {person:,
SSN:,
driverLicense:,
email:,
person_error:,
SSN_error:,
driverLicense_error:,
address: ,
email_error:}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))

def post(self):
person_name = self.request.get(person)
user_nacionality = self.request.get('nacionality')
user_profession = self .request.get('profession')
user_maritalStatus = self.request.get('maritalStatus')
user_SSN = self.request.get('SSN')
user_email = self.request .get('email')
user_driverLicense = self.request.get('driverLicense')
person_error =
SSN_error =
driverLicense_error =
geted_email_error =
address = self.request.get('address')
contractType = self.request.get(contractType)
owner = self.request.get如果(person_name和valid_person(person_name))和(user_SSN和valid_SSN(user_SSN))和((不是user_email)),








$ b )或(user_email和valid_email(user_email))):
a = People(firstName = person_name,
nacionality = user_nacionality,
maritalStatus = user_maritalStatus,
profession = user_profession,
SSN = int(user_SSN),
driverLicense = int(user_driverLicense)
#address = user_address

a.put()
self.redirect your_contract?person =%s& nacionality =%s& profession =%s& maritalStatus =%s& SSN =%s& driverLicense =%s& email =%s& witness =%s& owner =%s& contractType = s& address =%s'%(person_name,user_nacionality,user_profession,user_maritalStatus,user_SSN,user_driverLicense,user_email,
witness,owner,contractType,address))

else:
如果不是person_name或不是valid_person(person_name):
person_error =哦不!这个人的名字是无效的!
如果不是user_SSN或没有valid_SSN(user_SSN):
SSN_error =哦不! SSN无效!
如果user_email并且不valid_email(user_email):
geted_email_error =哦不!电子邮件无效!
template_values = {person:person_name,
nacionality:user_nacionality,
maritalStatus:user_maritalStatus,
profession user_profession,
SSN:user_SSN,
driverLicense:user_driverLicense,
email:user_email,
person_error:person_error,
SSN_error SSN_error,
driverLicense_error:user_driverLicense,
address:address,
email_error:geted_email_error}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))

class your_contractHandler(webapp2.RequestHandler):
def get(self):
geted_person_name = self .request.get('person')
geted_user_nacionality = self.request.get(nacionality)
geted_user_profession = self.request.get(profession)
geted_user_maritalStatus = self.request .get('maritalStatus')
geted_user_SSN = self.request.get('SSN')
geted_user_email = self.request.get('email')
geted_user_driverLicense = self.request.get ('driverLicense')
geted_person_error =
geted_SSN_error =
geted_driverLicense_error =
geted_address = self.request.get('address')
geted_owner = self.request.get(owner)
geted_witness = self.request.get(witness)
geted_contractType = self.request.get(contractType)
geted_dateToday = dateToday ()
your_contract = jinja_environment.get_template('your_contract.html')
your_contract_values = {person:geted_person_name,
nacionality:geted_user_nacionality,
maritalStatus:geted_user_maritalStatus ,
profession:geted_user_profession,
SSN:geted_user_SSN,
driverLicense:geted_user_driverLicense,
address:geted_address,
email:geted_user_email ,
contractType:geted_contractType,
dateContract:geted_dateToday,
}
template = jinja_environment.get_template('index.html')
self.response。 out.write(your_contract.render(your_contract_values))

class People(db.Model):
name = db.StringProperty(required = True)
nacionality = db.StringProperty (必需= True)
maritalStatus = db.StringProperty(必需= True)
profession = db.StringProperty(必需= True)
SSN = db.IntegerProperty b driverLicense = db.IntegerProperty(required = True)
#address = db.PostalAdressProperty(required = True)
#condition = db.StringProperty(required = False,choices = set
$ b ## class Acts(db.Model):
## firstPart = db.StringProperty(required =$ True)
## secondPart = db.StringProperty(必需= True)
## contractNumber = db.IntegerProperty(必需= False)
## contractDate = db.DateProperty(auto_now_add = True)
## contractDraft = db.TextProperty(required = True)


app = webapp2.WSGIApplication(['',MainHandler),('/ your_contract',your_contractHandler )],
debug = True)


解决方案

您的代码中有几个问题,从设计开始。



您应该有两个类存储在数据存储区(Contract和Person)
如果你使用NDB,你可以有一个结构化的属性为人的合同,但我们将保持简单。)



合同可以有任何你需要的东西一个合同然后有一个
people = ListProperty(db.Key)



在放置一个模型实例后,db.key与钥匙。



例如,在POST之后的重定向中,你会有类似$ b的东西$ b self.redirect('/ your_contract?person =%s'%a.key()')



要加载存储的人,你会:
person = db.get(self.request.get('person'))



如果你传递多个人键,你必须仔细检查webob文档如何在querystring中使用相同的键读取多个值,但我知道它会作为列表返回。



希望这有助于


I'm new to programming and I'm trying to grasp the concept of the GAE datastore. I'm trying to build an app to make it easy write contracts (http://contractpy.appspot.com). In the moment, I'm passing all the values I need to render the contract template from URL, this way:

self.redirect('/your_contract?person=%s&nacionality=%s&profession=%s&maritalStatus=%s&SSN=%s&driverLicense=%s&email=%s&witness=%s&owner=%s&contractType=%s&address=%s' % (person_name, user_nacionality, user_profession, user_maritalStatus, user_SSN, user_driverLicense, user_email,
#witness, owner, contractType, address))

But doing so, it remains limited to one person (and, in the future, I'll need to render several persons data in the same contract).

Instead of doing that, I'd like to use GAE datastore query to fill the variable values of the template "your_contract.html".

I know it's a simple question, but GAE datastore is completely obscure to me (I didn't grasp yet "the zen of the datastore", but I understand a little of SQL) and I'm learning OOProgramming just now. I read this article and I'v tried to follow this sample (Google guess_booK sample), but they were not enough for this brain. So, what is the best way to do this query, to render several persons data in one template? (Class Person is in the code bellow)

I was thinking this way: pass through URL a list with one data of each person (ex: Driver's License number):

self.redirect('/your_contract?driverLicense=%s' % (driverLicenseList))

And, in the handler "your_contract", use the value of "diverLicenseList" (after interact the list) to query GAE datastore, like this:

x = self.request.get('SSN')
contractingParty = db.GqlQuery("SELECT FROM Person WHERE SSN IS x")

Is this the right path? Thanks in advance for any help!

My original code (before doing GAE query) is here:

# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os

import webapp2

import jinja2

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

import re

from google.appengine.ext import db

USER_RE = re.compile(r"^[a-zA-Z0-9_ -]{3,20}$")
def valid_person(person):
    return USER_RE.match(person)

PASS_RE = re.compile(r"^.{3,20}$")
def valid_SSN(SSN):
    return PASS_RE.match(SSN)

EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
def valid_email(email):
    return EMAIL_RE.match(email)

import time

import datetime

def dateToday():
    today = datetime.datetime.today()
    todayDay = str(today.day)
    todayMonth = str(today.month)
    monthExt = {'1':' January ', '2':'February', '3':' March ', '4':'April', '5':'May', '6':'June', '7':' July ', '8':'August', '9':'September', '10':'October', '11':'November ', '12':'December'}
    todayYear = str(today.year)
    return(todayDay + ' of  ' + monthExt[todayMonth] + ' of ' + todayYear)

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {"person": "",
                                       "SSN": "",
                                       "driverLicense": "",
                                       "email":"",
                                       "person_error": "",
                                       "SSN_error": "",
                                       "driverLicense_error": "",
                                       "address": "",
                                       "email_error": ""}
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))

    def post(self):
        person_name = self.request.get("person")
        user_nacionality = self.request.get('nacionality')
        user_profession = self.request.get('profession')
        user_maritalStatus = self.request.get('maritalStatus')
        user_SSN = self.request.get('SSN')
        user_email = self.request.get('email')
        user_driverLicense = self.request.get('driverLicense')
        person_error = ""
        SSN_error = ""
        driverLicense_error = ""
        geted_email_error = ""
        address = self.request.get('address')
        contractType = self.request.get("contractType")
        owner = self.request.get("owner")
        witness = self.request.get("witness")

        if (person_name and valid_person(person_name)) and (user_SSN and valid_SSN(user_SSN)) and ((not user_email) or (user_email and valid_email(user_email))):
            a = People(firstName = person_name,
                                   nacionality = user_nacionality,
                                   maritalStatus = user_maritalStatus,
                                   profession = user_profession,
                                   SSN = int(user_SSN),
                                   driverLicense = int(user_driverLicense)
                                   #address = user_address
                                   )
            a.put()
            self.redirect('/your_contract?person=%s&nacionality=%s&profession=%s&maritalStatus=%s&SSN=%s&driverLicense=%s&email=%s&witness=%s&owner=%s&contractType=%s&address=%s' % (person_name, user_nacionality, user_profession, user_maritalStatus, user_SSN, user_driverLicense, user_email,
witness, owner, contractType, address))

        else:
            if not person_name or not valid_person(person_name):
                person_error = "Oh no!!! this person name isn't valid!"
            if not user_SSN or not valid_SSN(user_SSN):
                SSN_error = "Oh no!!! SSN isn't valid!"
            if user_email and not valid_email(user_email):
                geted_email_error = "Oh no!!! e-mail isn't valid!"
            template_values = {"person": person_name,
                                "nacionality": user_nacionality,
                                "maritalStatus": user_maritalStatus,
                                "profession": user_profession,
                                "SSN": user_SSN,
                                "driverLicense": user_driverLicense,
                                "email": user_email,
                                "person_error": person_error,
                                "SSN_error": SSN_error,
                                "driverLicense_error": user_driverLicense,
                                "address": address,
                                "email_error": geted_email_error}
            template = jinja_environment.get_template('index.html')
            self.response.out.write(template.render(template_values))

class your_contractHandler(webapp2.RequestHandler):
    def get(self):
        geted_person_name = self.request.get('person')
        geted_user_nacionality = self.request.get("nacionality")
        geted_user_profession = self.request.get("profession")
        geted_user_maritalStatus = self.request.get("maritalStatus")
        geted_user_SSN = self.request.get('SSN')
        geted_user_email = self.request.get('email')
        geted_user_driverLicense = self.request.get('driverLicense')
        geted_person_error = ""
        geted_SSN_error = ""
        geted_driverLicense_error = ""
        geted_address = self.request.get('address')
        geted_owner = self.request.get("owner")
        geted_witness = self.request.get("witness")
        geted_contractType = self.request.get("contractType")
        geted_dateToday = dateToday()
        your_contract = jinja_environment.get_template('your_contract.html')
        your_contract_values = {"person":geted_person_name,
                                "nacionality":geted_user_nacionality,
                                "maritalStatus": geted_user_maritalStatus,
                                "profession": geted_user_profession,
                                "SSN":geted_user_SSN,
                                "driverLicense":geted_user_driverLicense,
                                "address":geted_address,
                                "email":geted_user_email,
                                "contractType":geted_contractType,
                                "dateContract":geted_dateToday,
                                }
        template = jinja_environment.get_template('index.html')
        self.response.out.write(your_contract.render(your_contract_values))

class People(db.Model):
    name = db.StringProperty(required = True)
    nacionality = db.StringProperty(required = True)
    maritalStatus = db.StringProperty(required = True)
    profession = db.StringProperty(required = True)
    SSN = db.IntegerProperty(required = True)
    driverLicense = db.IntegerProperty(required = True)
#    address = db.PostalAdressProperty(required = True)
#    condition = db.StringProperty(required = False, choices=set(["buyer", "seller", "renter", "owner", "witness"]))

##class Acts(db.Model):
##    firstPart = db.StringProperty(required = True)
##    secondPart = db.StringProperty(required = True)
##    contractNumber = db.IntegerProperty(required = False)
##    contractDate = db.DateProperty(auto_now_add=True)
##    contractDraft = db.TextProperty(required = True)


app = webapp2.WSGIApplication([('/', MainHandler), ('/your_contract', your_contractHandler)],
                              debug=True)

解决方案

There are several issues in your code, starting with the design.

You should have two classes that are getting stored in the datastore (Contract and Person) (If you were using NDB you could have a contract with a structured Property for the Person, but we'll stay simple.)

The Contract could have whatever things you need for a contract and then have a people = ListProperty(db.Key)

After you put() a model instance the db.key() will be populated with the key. That's what you should be passing around to other parts of your code and storing in the ListProperty above.

For example in your redirect after the POST you would have something like self.redirect('/your_contract?person=%s' % a.key()')

To load the stored person you would do: person = db.get(self.request.get('person'))

If you are passing multiple person keys you'll have to double check the webob documentation on how to read multiple values with same key in querystring, but I know it comes back as a list.

Hope this helps

这篇关于如何查询GAE数据存储区以呈现模板(新手级)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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