欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

flask框架写接口

程序员文章站 2022-07-08 16:28:31
采用 flask 框架,写一个简单的接口from flask import Flask, jsonify, requestapp = Flask(__name__)@app.route('/hello',methods=['GET'])def hello(): name = 'world' if 'name' in request.args: name = request.args['name'] data = {'data': 'hello ' +...

采用 flask 框架,写一个简单的接口

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/hello',methods=['GET'])
def hello():
    name = 'world'
    if 'name' in request.args:
        name = request.args['name']
    data = {'data': 'hello ' + name}
    return jsonify(data)

if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.run(port=5001)

程序启动后输出:

* Serving Flask app "tmp" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
127.0.0.1 - - [12/Nov/2020 15:13:08] "GET /hello?name=nikey HTTP/1.1" 200 -
127.0.0.1 - - [12/Nov/2020 15:13:14] "GET /hello?name=test HTTP/1.1" 200 -

访问url:http://127.0.0.1:5001/hello?name=test

输出json数据:{"data":"hello test"}

 

访问url:http://127.0.0.1:5001/hello

输出json数据:{"data":"hello world"}

 

跨域问题

  • 接口提供给web使用时,ajax调用会遇到跨域问题,需修改response,设置 Access-Control-Allow-Origin 来解决
from flask import Flask,jsonify,request,make_response

# 初始化
app = Flask(__name__)

# 通过python装饰器的方法定义一个路由地址/hello,接口的uri
@app.route('/hello', methods=['GET'])
def hello():
    name = 'world'
    if 'name' in request.args:
        name = request.args['name']
    data = jsonify({'data': 'hello '+ name})

    # 解决ajax请求跨域问题
    res = make_response(data)
    res.headers['Access-Control-Allow-Origin'] = '*'

    print("返回结果是:", res)
    print(type(res))
    print(res.json)
    print(res.status)
    print(res.status_code)
    print(res.data)
    print(res.response)
    print(dir(res))
    print("================================")

    return res

if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    # host设置0.0.0.0的话可以使用公网ip访问
    # port是设置的端口号,port不填的话默认5000
    app.run(
        host='0.0.0.0',
        port=5001,
        debug=True
        )

输出结果:

 * Detected change in 'D:\\Nikey\\Python\\PyCharm\\basicProgram\\爬虫\\异步爬虫\\tmp.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 270-044-639
 * Running on http://0.0.0.0:5001/ (Press CTRL+C to quit)
返回结果是: <Response 28 bytes [200 OK]>
<class 'flask.wrappers.Response'>
{'data': 'hello test3'}
200 OK
200
b'{\n  "data": "hello test3"\n}\n'
[b'{\n  "data": "hello test3"\n}\n']
['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cached_json', '_ensure_sequence', '_get_data_for_json', '_is_range_request_processable', '_on_close', '_process_range_request', '_status', '_status_code', '_wrap_response', 'accept_ranges', 'access_control_allow_credentials', 'access_control_allow_headers', 'access_control_allow_methods', 'access_control_allow_origin', 'access_control_expose_headers', 'access_control_max_age', 'add_etag', 'age', 'allow', 'autocorrect_location_header', 'automatically_set_content_length', 'cache_control', 'calculate_content_length', 'call_on_close', 'charset', 'close', 'content_encoding', 'content_language', 'content_length', 'content_location', 'content_md5', 'content_range', 'content_security_policy', 'content_security_policy_report_only', 'content_type', 'data', 'date', 'default_mimetype', 'default_status', 'delete_cookie', 'direct_passthrough', 'expires', 'force_type', 'freeze', 'from_app', 'get_app_iter', 'get_data', 'get_etag', 'get_json', 'get_wsgi_headers', 'get_wsgi_response', 'headers', 'implicit_sequence_conversion', 'is_json', 'is_sequence', 'is_streamed', 'iter_encoded', 'json', 'json_module', 'last_modified', 'location', 'make_conditional', 'make_sequence', 'max_cookie_size', 'mimetype', 'mimetype_params', 'on_json_loading_failed', 'response', 'retry_after', 'set_cookie', 'set_data', 'set_etag', 'status', 'status_code', 'stream', 'vary', 'www_authenticate']
================================
127.0.0.1 - - [12/Nov/2020 15:44:10] "GET /hello?name=test3 HTTP/1.1" 200 -

 

 

问题:运行flask接口程序后,报错“TypeError: required field "type_ignores" missing from Module”

解决方法:升级Werkzeug包为0.15.5版本,或者更高版本,即可解决问题;

升级Werkzeug:pip install --upgrade Werkzeug

 

 

 

本文地址:https://blog.csdn.net/nikeylee/article/details/109644335

相关标签: Python