Coursera 笔记

Module 02 · Web App Deployment using Flask

Module 2 Cheatsheet: Web App Deployment using Flask模块 2 速查表:使用 Flask 进行 Web 应用部署

Coursera ↗

Estimated time needed: 5 minutes
预计所需时间:5 分钟

Package/Method  包/方法 Description  描述 Code Example  代码示例
Flask Used to instantiate an object of the Flask class named app.
用于实例化名为 app 的 Flask 类对象。
from flask import Flask
app = Flask(__name__)
@app.route decorator  @app.route 装饰器 A decorator in Flask used to map URLs to specific functions in a Flask application.
Flask 中的一个装饰器,用于将 URL 映射到 Flask 应用程序中的特定函数。
@app.route('/')
def hello_world():
    return "My first Flask application in action!"
200 OK status  200 OK 状态 Flask servers automatically return a 200 OK status when you return from the @app.route method. 200 is also returned by default when you use the jsonify() method to respond to a request. A successful response with a status code of 200 will be sent back when the given code executes.
当您从@app.route 方法返回时,Flask服务器会自动返回 200 OK 状态。当您使用 jsonify()方法响应请求时,默认也会返回 200。当给定代码执行时,将发送一个状态码为 200 的成功响应。
@app.route('/')
def hello_world():
    return ("My first Flask application in action!", 200)
Error 404  错误 404 400 indicates an invalid request. This status could imply the parameters are missing or improper or the request is invalid in another way.
400 表示请求无效。此状态可能意味着参数缺失或不正确,或者请求以其他方式无效。

401 indicates the credentials are missing or invalid.
401 表示凭证缺失或无效。

403 implies that the client credentials are not sufficient to fulfill the request.
403 意味着客户端凭证不足以完成请求。

404 If the server is unable to find the resource, it returns a 404 status.
404 如果服务器无法找到资源,则返回 404 状态。

405 indicates that the requested operation is not supported.
405 表示请求的操作不受支持。
@app.route('/')
def search_response():
    query = request.args.get("q")
    if not query:
        return {"error_message": "Input parameter missing"}, 422
    # fetch the resource from the database
    resource = fetch_from_database(query)
    if resource:
        return {"message": resource}
    else:
        return {"error_message": "Resource not found"}, 404
Error 500  错误 500 500 is used when there is an error on the server.
当服务器出错时使用 500。
@app.errorhandler(500)
def server_error(error):
    return {"message": "Something went wrong on the server"}, 500

Author(s) 作者

Andrew Pfeiffer   安德鲁·普菲弗

Other Contributor(s) 其他贡献者

Abhishek Gagneja, Sina Nazeri
Abhishek Gagneja,Sina Nazeri