Stay Hungry,Stay Foolish!

Flask 入门

Flask

http://flask.pocoo.org/docs/1.0/

 

Welcome to Flask

Flask: web development, one drop at a time

Welcome to Flask’s documentation. Get started with Installation and then get an overview with the Quickstart. There is also a more detailed Tutorial that shows how to create a small but complete application with Flask. Common patterns are described in the Patterns for Flask section. The rest of the docs describe each component of Flask in detail, with a full reference in the API section.

Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit. The documentation for these libraries can be found at:

 

还包括

User’s Guide

API Reference

 

Quick Start

http://flask.pocoo.org/docs/1.0/quickstart/#quickstart

A Minimal Application

A minimal Flask application looks something like this:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

 

 

Variable Rules

You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % subpath

 

HTTP Methods

Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

 

官方例子

https://github.com/pallets/flask/tree/1.0.2/examples

包括一个MVC模式的博客栗子,和 js 通过json与后台交互数据的例子。

是学习flask的好资料。

 

安装过程遇到问题:

https://cn.bing.com/search?q=sqlite3.OperationalError%3a+no+such+table%3a+post&pc=MOZI&first=1&FORM=PQRE1

需要初始化数据库, 见样例的官方文档说明.

 

 

扩展

http://flask.pocoo.org/docs/1.0/extensions/#extensions

http://flask.pocoo.org/extensions/

包括 resetful jsonapi 等扩展工具。

 
posted @ 2018-05-26 09:47  lightsong  阅读(268)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel