Flask form question, how is this name passed in?

Source: Internet
Author: User

Reply content:

Laxatives!
Do not look at the source of the form, but it should be this:

First, you need to understand the basic operating mechanism of MVC (or MTC) like flask.
-For Flask view, you need to know the WSGI agreement (if not clear, please google it yourself).

The lower level (the logical bottom) of the HTTP utils (flask with Werkzeug) will parse the client's HTTP requests, etc., and build it as WSGI environment (containing the request and other information).

WSGI server processes the process request by building a environ based on the WSGI protocol, passing it into the Flask app instance (the Flask app that is implemented by the WSGI framework), Flask app Instance uses this environ and his own "Start_response" method (which is also the UWSGI protocol) to complete the request processing and response.

Flask has a Request object at the thread level (or Greenlet). Before the real process response, throw the Environ into the request object, and then the request follows your thread to become a tacit friend ~ ~ Until the response is complete or the thread is finished.

Views inside of that Tuo Tuo of the role of the route is what pinch? This is the URL routing, I am on your site to order a specific url,flask how to meet you. You have to say what you want.

So when does the views come into use? Nonsense, of course, after receiving and understanding the request until the response.

Well, Flask app instance the URL you requested from the request object when dealing with your needs, which is the equivalent of a key, and then the app instance find the corresponding lock according to the key (the processing logic you want, is the function under the route in the views), this lock ah, once she has been opened, to meet your needs of the moment is fast ~ ~
P.s. As to how to match this lock, this is the URL mapping, is a bunch of regular matching (do not underestimate this, if you have used Flask Blueprint, you will understand that writing such a mapping is also a good thing of the hi)

-Model & Controller?
Your demand is actually to flask to you response,response actually is the data (whether it is the RESTful API or template form, it is you to be out of the information).

How did the data come about? You get it from the database (broadly, including SQL & NoSQL db, Memory-level cache, disk files, and so on), as to the source of the data, maybe you plug it in or cry from somewhere else.

Model is to do this work, but it is more abstract, the database operations into the operation of the Python object (this is the famous ORM, in fact, there is no egg, orm write more you even query optimization forget, if you have a higher performance demand also have a lot of time, I'm going to get my own high-efficiency search solution, I'm not less%>_<% by this stuff.

Controller this thing you can actually not, but in order to do the logical separation, let you masturbate the business of the beautiful or use it.

OK, said so much, do not know if anyone can read, if not read, let me think about it ~ ~

========================================================================
In short, when you use flask as a application, MVC does its best to heap up the logic that you generate data, and you don't have to worry about it.

Damn, you can finally get back to your question:

First look at the form of this thing:
from flask.ext.wtf import Formfrom wtforms import StringField, SubmitFieldfrom wtforms.validators import Requiredclass NameForm(Form):    name = StringField('What is your name?', validators=[Required()])    submit = SubmitField('Submit')
Flask's request is a global variable (the exact point is a thread local variable, which can be considered as a global variable), I do not see the Flask form-related code, all here to guess, It should be nameform. This class is directly used to request.from the post form data dictionary to verify, and because the request online range is global, all nameform can be used without parameters to get to form data nameform () Should be inherited from Wtform, first understand this thing.
I was confused, too. Flask Web Developmentused to beFLASK_WTFmodule, while some tutorials usewtformsmodule. this iswtformsthe form validation routing function@app. Route('/register ', Methods=[' GET ', ' POST '])def Register():    form = Registrationform(Request.form)    if Request.Method == ' POST '  and form.Validate():             PassIn contrast, you will find that there are three differences between the two1.Registrationforminstantiation is used.Request.form, which is not used in your example. 2.in your case, there is no validation form.POSTor isGETmethod, which is used in the above example.Request.Method == ' POST '3.one isform.Validate(), one isform.Validate_on_submit(). VisibleFLASK_WTFin the module.Form class onwtformsin theFormclass is encapsulated. putRequest.form and theRequest.Method == ' POST 'encapsulated in it. A comparison of the code should be easy to understand. 
Try to simplify explaining the problem:
1. When the route triggers the index view function.
form = Nameform () This statement creates a form instance object, which means that the form is created.
2, if it is the first time to access the page containing this form is a GET request

If Form.validate_on_submit () This judgment is false, the following block of statements is not executed.
3. If it is a POST request
This time, the form already exists.
If Form.validate_on_submit () This judgment is true, the following block of statements is to be executed.
Name = Form.name.data This statement gets the form property value when it is post.

4, whether post, or get
Return render_template (' index.html ', Form=form, Name=name)
This statement has to be executed.


How to get the value of form forms, see flask.request.
classFlask.requestapi-flask Documentation (0.10)

To access incoming request data, you can use the global requestobject. Flask parses incoming request data for both and gives youaccess to it through that global object. Internally Flask Makessure that's always get the correct data for the active thread if youare in a multithreaded environ ment.

This is a proxy. See Notes on Proxies for more information.

The request object is an instance of a requestsubclass and provides all of the attributes Werkzeug defines. Thisjust shows a quick overview of the most important ones.

Can take a look at @wang Harvey and @ Zhu Tian First answer, and then go to the FLASK-WTF definition form class source code, in the form class comments, https:// Github.com/lepture/flas K-wtf/blob/master/flask_wtf/form.py#l41-l42 These two lines should be able to clearly explain the problem of the main question. Here's a quote:
If formdata is not specified, this will use flask.request.form.Explicitly pass formdata = None to prevent this.
= = Although @wang Harvey's answer is very good, but I do not think completely solve the landlord problem ah ... No, @ not on the highest ticket answer the Lord ...

Landlord do not know how to get out of the name? Then the name is defined. Python is a strongly typed, directly defined name to store form.name.data data.

So, how did Form.name.data get out? Form.name is a data that you define in the form, its name (see document]forms-wtforms 2.0.3dev Documentation ) is name (you define it yourself).

So what's the use of passing form.name.data to name? We see that it is redirected to index.html inside, then we open index.html (for this I have been dedicated to open for a long time useless file checkout), we can see

Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!

The following is my personal understanding, first time the first request, is a GET request, rendered an empty table page, when you fill out the item, click Submit is already a second request, POST request, this time the table content sent to the server, and then assign value. Master, I use the same book as you. I am self-taught program, read the basic Python grammar is strong to the book. At the beginning of the real HTML will not ... Then to now two months more, embarrassed to see the sixth chapter seventh chapter ...
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.