栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Build a CRUD App with SQLAlchemy - Getting User Data in Flask (1)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Build a CRUD App with SQLAlchemy - Getting User Data in Flask (1)

There are 3 methods of getting user data from a view to a controller.

  • URL query parameters
    URL query parameters are listed as key-value pairs at the end of a URL, preceding a “?” question mark. E.g. www.example.com/hello?my_key=my_value.
value1 = request.args.get('my_key')
value2 = request.args.get('foo', 'my default')
  • Forms
    request.form.get(name) reads the value from a form input control (text input, number input, password input, etc) by the name attribute on the input HTML element.
username = request.form.get('username')
password = request.form.get('password')
result = request.form.get('foo', 'my default')
  • JSON
    request.data retrieves JSON as a string. Then we’d take that string and turn it into python constructs by calling json.loads on the request.data string to turn it into lists and dictionaries in Python.
For data type application/json, use request.data

data_string = request.data
data_dictionary = json.loads(data_string)

Using HTML form submission to get the data

  • Forms take an action (name of the route) and method (route method) to submit data to our server.
  • The name attribute on a form control element is the key used to retrieve data from request.get(key).
  • All forms either define a submit button, or allow the user to hit ENTER on an input to submit the form.


request.form.get('bar2')

Form methods POST vs GET

Using the POST method, then you should use the request.form.get(name)


Using the GET method, then you should use the value1 = request.args.get(‘my_key’)

“Response body” should be corrected to “Request body”, throughout, since the client is sending off a request.

The way form data traverses from the client to server differs based on whether we are using a GET or a POST method on the form.

The POST submission

  • On submit, we send off an HTTP POST request to the route /create with request body
  • The request body stringifies the key-value pairs of fields from the form (as part of the name attribute) along with their values.

The GET submission

  • Sends off a GET request with URL query parameters that appends the form data to the URL
  • Ideal for smaller form submission.

Notes: POSTs are ideal for longer form submissions, since URL query parameters can only be so long compared to request bodies (max 2048 characters). Moreover, forms can only send POST and GET requests, and nothing else.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/503653.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号