HTTP post with GAE (and WTForms)

Hi how can I get the variables in a HTTP post with WTForms when the post is done with a blobstoreuploadhandler and preferably also with i18n localized messages for validation? This is my code that is not working:

class AdForm(Form):
    name = TextField(_('Name'))
    title = TextField(_('title'))
    text = TextAreaField(_('Text'),widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phonenumberhide = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))

When I try to access the data posted via the form the data turns out as None :

form = AdForm(data=self.request.POST)
if form.title:
  logging.info('getting title:'+form.title.data)
  ad.title = form.title.data
  ad.save()

The above does not save anything to the datastore and this is the template where it's coming from

  <div class="labelform">
         <div class="labelform" style="clear:left;">
    <label> {% filter capitalize %}{% trans %}title{% endtrans %}{% endfilter %}:</label>
  </div>
  </div>
  </td><td>
{{ form.title }}{% if form.title.errors %}
        <ul class="errors">{% for error in form.title.errors %}<li>{{ error }}</li>{% endfor %}</ul>
    {% endif %}

Can you help me? There's something in the WTForms manual about appengine but I couldn't find a working example.

Update

I added validation tests and I still can't access the variables:

logging.info('getting requests')
if form.validate():
  if form.title:
    logging.info('getting title:'+form.title.data)
    ad.title = form.title.data
    ad.save()
    ad.put()

Logging output:

INFO 2011-11-05 23:17:24,653 main.py:1504] getting requests INFO
2011-11-05 23:17:24,653 main.py:1507] getting title:

Update 2

I removed the WTForms dependence and it is still not working. The line logging.info('getting data:'+ self.request.get('title', '0')) only outputs 0 even though the form is just a regular http post form:

 <form action="{{form_url}}" name="upload" method="post" enctype="multipart/form-data" accept-charset="utf-8">

Update 3

This minimal config with no WTForms and no Jinja works so it's probably something with Jinja when this bare-bones example works with webapp2 and python 2.7 where I'm going to add the faulty code line by line to troubleshoot:

class GuestPage(BaseHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <body>
              <form action="/sign" method="post">
                <div><textarea name="content" rows="3" cols="60"></textarea></div>
                <div><input type="submit" value="Sign Guestbook"></div>
              </form>
            </body>
          </html>""")


class Guestbook(BaseHandler, I18NHandler, blobstore_handlers.BlobstoreUploadHandler):
    csrf_protect = False

    def post(self):
        self.response.out.write('<html><body>You wrote:<pre>')
        self.response.out.write(self.request.get('content'))
        self.response.out.write('</pre></body></html>')


app = webapp2.WSGIApplication([        ('/guest', GuestPage),
                                      ('/sign', Guestbook),

...

Update 4

My back to basics is working with Jinja so I suppose I just build on this example and see where it breaks:

class GuestPage(BaseHandler):
    def get(self):
    self.render_jinja('form_jinja')

class Guestbook(BaseHandler, I18NHandler, blobstore_handlers.BlobstoreUploadHandler):
    csrf_protect = False

    def post(self):
        self.response.out.write('<html><body>You wrote:<pre>')
        self.response.out.write(self.request.get('content'))
        self.response.out.write('</pre></body></html>')

Update 5

I can reproduce the error with this minimal example that can't access the http post variable:

class GuestPage(webapp2.RequestHandler):
    def get(self):

        self.response.out.write("""
          <html>
            <body>
              <form action=" """ +blobstore.create_upload_url('/sign')+ """ " method="post">
                <div><textarea name="content" rows="3" cols="60"></textarea></div>
                <div><input type="submit" value="Sign Guestbook"></div>
              </form>
            </body>
          </html>""")


class Guestbook(blobstore_handlers.BlobstoreUploadHandler):

    def post(self):
        self.response.out.write('<html><body>You wrote:<pre>')
        self.response.out.write(self.request.get('content'))
        self.response.out.write('</pre></body></html>')


app = webapp2.WSGIApplication([       ('/guest', GuestPage),
                                      ('/sign', Guestbook),

Update 6

From the guestbook example code with blobstoreuploadhandler I can upload a file on the production server so I could make a working example that uses the blobstoreuploadhandler that I will try to build on for my use case.

Update 7

I could get my original code so that everything works except the blob transfer. I suspect a diff between dev_appserver and production that I posted to the google appengine group about. We'll see how it progresses.

Update 8 Here's another common use how nothing works when you add WTForms:

    logging.info('getting data:'+ self.request.get('title', '0'))
    logging.info('http post data:'+ str(self.request.post))
    form = AdForm(formdata=self.request.data)
    logging.info('populated form')
    logging.info('form data:' + str(form.formdata))
    if form.validate():
      if form.title:
        logging.info('getting title:'+str( form.get('title') ) )
        ad.title = form.title.data      ad.save()       ad.put()
      if form.text:
        logging.info('getting text:' +str(form.text))
        ad.text = form.text.data
      if self.request.get('currency'):
        ad.currency = self.request.get('currency')
      if self.request.get('cg'):
        ad.category = form.cg.data
      if self.request.get('company_ad') == '1':
        ad.company_ad = True
      ad.put()
    else:
      logging.info('form did not validate')
except Exception, ex:
    logging.info('there occured exception %s', str(ex))

INFO 2011-11-09 12:11:50,868 main.py:1385] getting data:TEST INFO 2011-11-09 12:11:50,868 main.py:1409] there occured exception post

Update 9

Finally the form populates it just doesn't validate. Thank you Sean for the info that got me further. Now I get past populated the form object with no exception but the exception occurs when I try to validate:

logging.info('getting data:'+ self.request.get('title', '0'))
form = AForm(self.request.POST)
logging.info('populated form')
if form.validate():
  logging.info('validated form')

The above code is logging the output:

INFO     2011-11-11 08:03:59,913 main.py:1387] getting data:TEST
INFO     2011-11-11 08:03:59,914 main.py:1390] populated form
INFO     2011-11-11 08:03:59,914 main.py:1412] there occured exception 'builtin_function_or_method' object is not iterable

What does the exception mean?

My form class is

class AForm(Form):
    name = TextField(_('Name'))
    title = TextField(_('title'))
    text = TextAreaField(_('Text'),widget=TextArea())
    phonenumber = TextField(_('Phone number'))
    phonenumberhide = BooleanField(_('Display phone number on site'))
    price = TextField(_('Price'))
    password = PasswordField(_('Password'))
    email = TextField(_('Email'))  
    category  = SelectField(choices=categories.keys)

I don't know anything about WTForm, but I'd guess that like Django forms, you need to call the validation function before you can access the data. In this case, it's form.validate() :

form = AdForm(formdata=self.request.POST)
if form.validate():
    ad.title = form.title.data

Daniel actually it is not data=self.request.POST that you need to pass to the form but formdata instead of data http://wtforms.simplecodes.com/docs/dev/forms.html#the-form-class

hope it will be usefull for all those who rushed through the doc as i did

链接地址: http://www.djcxy.com/p/61750.html

上一篇: 当我使用带有Flask的POST时,我遇到了wtforms selectfields的问题

下一篇: GAE(和WTForms)的HTTP帖子