<commit_before><commit_msg>重温一下flask框架！<commit_after>---
layout: post
title: flask重温
category: 学习
keywords: 学习,2016
---

## flask 小型可扩展框架， 但是功能不少！


## hello world!

```

# -*- coding: utf-8 -*-

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>hello world!</h1>'

if __name__ == '__main__':
    app.run(debug=True)


```

要点
__name__ 决定程序的根目录，用来找资源的文件

app.run 使用程序进入轮询

## 动态路由

```

@app.route('/user/<name>')
def user(name):
    return '<h1> hello, %s!</h1>' % name


```

要点：
就是让参数加在路由上


## 上下文全局变量
current_app  激活的程序实例
g       程序上下文
request 请求上下文
session 用户会话


```

@app.route('/request')
def headers():
    return '%s' % request.headers


```

## 请求钩子

before_first_request
before_request
after_request
teardown_request


## 使用flask扩展
使用flask-script 支持命令行选项
pip install flask-script

```

from flask.ext.script import Manager
manager = Manager(app)


manager.run()


```


```

# python hello.py
usage: hello.py [-?] {shell,runserver} ...

positional arguments:
  {shell,runserver}
    shell            Runs a Python shell inside Flask application context.
    runserver        Runs the Flask development server i.e. app.run()

optional arguments:
  -?, --help         show this help message and exit


```



要点：

扩展放在flask.ext下



## 完整实例

```

# -*- coding: utf-8 -*-

from flask import Flask
from flask.ext.script import Manager
from flask import request


app = Flask(__name__)
manager = Manager(app)


@app.route('/')
def index():
    return '<h1>hello world!</h1>'


@app.route('/user/<name>')
def user(name):
    return '<h1> hello, %s!</h1>' % name


@app.route('/request')
def headers():
    return '%s' % request.headers


if __name__ == '__main__':
    manager.run()


```


## 参考

flask web 开发 基于python的web应用开发实践

{'fraction_non_alphanumeric': 0.15626756604834177, 'fraction_numerical': 0.007869589657110737, 'mean_word_length': 3.320388349514563, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3604335', 'n_tokens_mistral': 789, 'n_tokens_neox': 764, 'n_words': 165}