任何Web应用程序都经常需要处理从用户那里收到的数据。这些数据可以是查询字符串、表单数据和JSON对象(JavaScript Object Notation)。像其他网络一样,该框架允许用户访问该请求的数据。本文将学习如何建立一个具有三个路由的flask应用程序,以接受查询字符串、表单数据或JSON对象中的数据。
这方面的要求。
- 在本地环境中安装Python
- 一个可用于生产的工具Pipenv,以便在python世界中获得最好的包装。
- 安装一个像Postman这样的工具来测试API端点。
设置Flask应用。
我们需要创建一个Flask应用来演示用户请求的不同方法。虽然演示应用程序使用了相对简单的结构来查看函数和路由,但这些可以应用于任何组织视图、蓝图或Flask-Via等扩展。
这其中涉及的步骤。
打开终端,运行以下命令mkdir flask_request_example ,创建一个项目目录。之后,通过这个命令导航到新目录:cd flask_request_example 。现在打开终端,通过运行以下命令安装Flask:pipenv install Flask 。这个pipenv 命令将创建一个 [virtualenv](https://blog.finxter.com/how-to-run-multiple-python-versions-on-windows/ "How To Run Multiple Python Versions On Windows?")和pipfile install flask 以及pipfile.lock 。通过使用pipenv shell 命令来启动Virtualenv的激活**。**
如何访问Flask请求中收到的数据?
Flask应用中的传入数据可以通过使用请求对象来访问。请求对象工具持有所有来自请求的传入数据,如IP地址、原始数据、HTTP方法、头文件、MIME类型、推荐人和其他东西。要访问Flask中的请求对象,我们需要通过flask import request这个命令从Flask库中导入它。一旦我们获得了对请求对象的访问权,我们就可以用它来查看任何函数。使用代码编辑器,如PyCharm 或任何其他编辑器,创建一个app.py 文件。为query-example,form-example, 和JSON- example 建立路由。
# import main Flask class and request object
from flask import Flask, request
# create the Flask app
app = Flask(__name__)
@app.route('/query-example')
def query_example():
return 'Query String Example'
@app.route('/form-example')
def form_example():
return 'Form Data Example'
@app.route('/json-example')
def json_example():
return 'JSON Object Example'
if __name__ == '__main__':
# run app in debug mode on port 5000 app.run(debug=True, port=5000)
如何启动该应用程序?
在完成app.py 的创建后,打开终端并通过以下命令启动应用程序 python app.py 。该应用程序将在5000端口启动,每个路由可以通过以下链接在浏览器中查看。
- https://127.0.0.1:5000/query-example (或 localhost:5000/query-example)
- http://127.0.0.1:5000/form-example(或 localhost:5000/form-example)
- http://127.0.0.1:5000/json-example(或localhost:5000/JSON-example)
这段代码将建立三个路由,每个路由将分别显示 "查询字符串示例"、"表单数据示例 "和"JSON对象**示例 "**的信息。
如何使用查询参数向网页传递数据?
我们添加到查询字符串中的URL参数很容易将数据传递给网页应用程序。我们中的许多人很可能在浏览时遇到了查询字符串。
查询字符串是什么样子的?
一个查询字符串看起来像这样。 **example.com?arg1=value1&arg2=value2**.
它总是以一个问号字符开始,并有两个值对,由一个安培号(&)分隔。任何查询字符串都有一个等号字符,然后是一个值字符。查询字符串在传递数据方面很方便,不需要用户采取行动。查询字符串可以在应用程序的某个地方生成,并附在URL上。当用户提出请求时,他们会自动得到他们所需的数据。表格也可以通过GET方法生成一个查询字符串。
如何将查询字符串添加到URL中?
首先,我们需要创建一个我们想要添加到URL中的键。假设我们有一个 "language "的键和一个 "Python "的值,以便在屏幕上显示编程语言名称。它将像这样工作。这里是我们的链接**http://127.0.0.1:5000/,在查询字符串之后,它变成了这样http://127.0.0.1:5000/query-example?language=Python**。导航到该URL现在将显示一个查询字符串例子的信息。
与此相关的重要观点。
我们需要对处理查询参数的部分也进行编程。代码将通过使用request.args.get('language') 或request.args['language'] 来读入语言键。
- 通过调用
request.args.get('language'),如果URL中不存在语言键,应用程序将继续运行。在这种情况下,该方法的结果将是None。 - 然而,通过调用
request.args['language'],如果URL中不存在语言键,应用程序将显示一个400错误。
所以为了避免这个问题,建议使用request.args.get() 。
代码示例
通过这段代码修改app.py 中的query-example 路线。
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
return '''<h1>The language value is: {}</h1>'''.format(language)
然后运行应用程序并导航到URL**http://127.0.0.1:5000/query-example?language=Python**。浏览器将以这种方式显示输出。
输出。The language value is: Python.
如何使用表单数据?
表单数据是已经作为帖子请求发送到任何路由的数据。表单数据将在幕后传递给应用程序,在URL中隐藏数据。
表单数据如何被传递给应用程序?
表单数据可以通过修改app.py 中的form-example 路由进行传递。这个修改将允许我们同时接受POST和GET请求,并以表单形式返回。
# allow both GET and POST requests
@app.route('/form-example', methods=['GET', 'POST'])
def form_example():
return '''<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'''
应用该代码,然后运行应用程序并导航到相应的URL**http://127.0.0.1:5000/form-example**。浏览器将显示一个带有两个输入字段的表单,输入语言和框架。如果是这样,那么就按提交按钮。这个表单将只对生成该表单的同一路线执行一个帖子请求。在view 函数中,我们需要检查请求模式是GET还是POST。如果是GET请求,那么只有我们可以显示表单。Post请求意味着我们要处理传入的数据。
如何处理这两种请求类型?
首先,我们必须通过这个代码例子修改app.py 中的form-example路线。
# allow both GET and POST requests
@app.route('/form-example', methods=['GET', 'POST'])
def form_example():
# handle the POST request
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the GET request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'''
之后,运行应用程序并导航到URL**http://127.0.0.1:5000/form-example**。在语言字段中填入框架的值,在python字段中填入Flask的值。然后按提交。浏览器将显示这样的输出。
输出。
The language value is: Python
The framework value is: Flask
JSON数据监控。
JSON 是JavaScript对象符号。JSON数据可以由一个调用路由的过程构建。一个有数组项目的嵌套JSON对象看起来像这样。通过这种结构,可以传递复杂的数据,而不是查询字符串和表单数据。Flask也可以有效地处理这种格式的数据。为了接受JSON数据,在app.py 中修改form-example路由,以接受POST请求,而忽略所有其他请求,如GET。
{
"language" : "Python",
"framework" : "Flask",
"website" : "Scotch",
"version_info" : {
"python" : "3.9.0",
"flask" : "1.1.2"
},
"examples" : ["query", "form", "json"],
"boolean_test" : true
}
代码示例。
@app.route('/json-example', methods=['POST'])
def json_example():
return 'JSON Object Example'
如何通过Postman为JSON对象发送自定义请求?
与查询字符串和表单数据发送JSON对象不同,Postman 将发送自定义请求到URL。在Postman 中添加URL,并将类型改为POST。在body标签中,改为raw,并从下拉菜单中选择JSON。
POST http://127.0.0.1:5000/json-example Body raw JSON
这些设置对于通过Postman发送JSON数据并通知Flask应用它收到JSON是必要的。现在把JSON复制到文本输入中。发送请求,并将返回一个JSON对象实例作为响应。响应可能会让人感到震惊,但这是意料之中的,因为处理JSON数据的代码没有了。让我们添加这段代码。
读取传入的JSON数据的代码。
在我们添加代码之前,我们需要进行一些设置。首先,我们将通过使用request.get_json() 功能将JSON对象中的所有内容分配给一个变量。这将把JSON对象转换为Python数据。现在将传入的请求数据分配到变量中,并通过在JSON-example路线中进行以下修改来返回。
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
language = request_data['language']
framework = request_data['framework']
# two keys are needed because of the nested object
python_version = request_data['version_info']['python']
# an index is needed because of the array
example = request_data['examples'][0]
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)
为什么JSON数据请求会失败?
当视图函数中访问的键丢失时,JSON对象请求主要失败。在发送请求之前,要确保其中有键,以避免这种情况。一旦符合键的存在,运行应用程序并使用Postman发送JSON请求。
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
language = None
framework = None
python_version = None
example = None
boolean_test = None
if request_data:
if 'language' in request_data:
language = request_data['language']
if 'framework' in request_data:
framework = request_data['framework']
if 'version_info' in request_data:
if 'python' in request_data['version_info']:
python_version = request_data['version_info']['python']
if 'examples' in request_data:
if (type(request_data['examples']) == list) and (len(request_data['examples']) > 0):
example = request_data['examples'][0]
if 'boolean_test' in request_data:
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)
输出。
The language value is: Python
The framework value is: Flask
The Python version is: 3.9
The item at index 0 in the example list is: query
The boolean value is: false
代码示例的参考资料
The postHow to Get the Data Received in a Flask Requestfirst appeared onFinxter.