flask学习笔记1【服务器程序基本结构】

一、使用virtualenv

1. 安装
python-virtualenv


为什么使用这个东西呢?
为每个程序单独创建虚拟环境可以保证程序只能访问虚拟环境中的包,从而保持 全局解释器的干净整洁,使其只作为创建(更多)虚拟环境的源。
使用虚拟环境还有个好处,那就是不需要管理员权限。

出现报错
Running virtualenv with interpreter /usr/bin/python2
New python executable in /home/young/桌面/venv/bin/python2
Also creating executable in /home/young/桌面/venv/bin/python
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 12: ordinal not in range(128)
ERROR: The executable /home/young/桌面/venv/bin/python2 is not functioning
ERROR: It thinks sys.prefix is u'/home/young/\u684c\u9762' (should be u'/home/young/\u684c\u9762/venv')
ERROR: virtualenv is not compatible with this system or executable



看提示,提示把中文路径转码了,看来这是个对中文路径很矫情的家伙,为了节省时间,我们
重新建立一个没有中文的路径
young@YOUNG:~/flaskLearning$ virtualenv venv
Running virtualenv with interpreter /usr/bin/python2
New python executable in /home/young/flaskLearning/venv/bin/python2
Also creating executable in /home/young/flaskLearning/venv/bin/python
Installing setuptools, pkg_resources, pip, wheel...done.

ok,这样就行了


2. 激活


看见这小标志就是激活了的意思
** 想返回原来的状态可以使用deactivate



二、服务器程序的基本结构
1. 一个基本的服务器
# 导入flask包
from flask import Flask
# 初始化flask app
app = Flask(__name__)
# 将构造函数的 name 参数传给 Flask 程序,这一点可能会让 Flask 开发新手心
# 生迷惑。Flask 用这个参数决定程序的根目录,以便稍后能够找到相对于程
# 序根目录的资源文件位置。

# 使用注解路由
@app.route('/')
def index():
	# 返回响应内容
	return '<h1>Hello World!</h1>'

if __name__ == '__main__':
	# 开启debug模式
	# debug模式是为了在修改代码的时候,服务器自动重启
	app.run(debug=True)



2. 路由

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

注意点
  • 尖括号中的内容就是动态部分,任何能匹配静态部分的 URL 都会映射到这个路由上
  • 路由中的动态部分默认使用字符串
  • 路由 /user/<int:id>只会匹配动态片段 id 为整数的 URL
  • Flask 支持在路由中使用 int 、 float 和 path 类型。
  • path 类型也是字符串,但不把斜线视作分隔符,而将其当作动态片段的一部分。
  • return要求是字符串,否则会报错
  • 如果路径中有动态变量,例如@app.route('/user/<name>')中的name,那么在函数应该有相应同名变量,例如def index(name);相反def index()和def index(test)都会报错
3. 启动



三、请求与响应
1. 程序上下文和请求上下文
Flask 从客户端收到请求时,要让视图函数能访问一些对象,这样才能处理请求。
请求对象 request 就是一个很好的例子,它封装了客户端发送的 HTTP 请求。


顾名思义,程序上下文就是整个服务程序的“全局变量”
请求上下文就是一个“请求响应”范围内的“全局变量”,如表中所描述。

Flask 在分发请求之前 激活(或推送)程序和请求上下文,请求处理完成后再将其删除。程
序上下文被推送后,就可以在线程中使用 current_app 和 g 变量。类似地,请求上下文
推送后,就可以使用 request 和 session 变量。

>>> from hello import app
>>> from flask import current_app
>>> current_app.name
...
RuntimeError: working outside of application context
>>> app_ctx = app.app_context()
>>> app_ctx.push()
>>> current_app.name
'hello'
>>> app_ctx.pop()



2. URL映射
Flask 使用
app.route 修饰器
或者
非修饰器形式的 app.add_url_rule()
生成映射。

查看生成的映射
(venv) $ python
>>> from hello import app
>>> app.url_map
Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/user/<name>' (HEAD, OPTIONS, GET) -> user>])

URL 映射中的 HEAD 、 Options 、 GET 是请求方法


3. 请求钩子(可以简单理解为AOP)
• before_first_request :注册一个函数,在处理第一个请求之前运行。
• before_request :注册一个函数,在每次请求之前运行。
• after_request :注册一个函数,如果没有未处理的异常抛出,在每次请求之后运行。
• teardown_request :注册一个函数,即使有未处理的异常抛出,也在每次请求之后运行。

在请求钩子函数和视图函数之间共享数据一般使用上下文全局变量 g 。

4. 响应
4.1返回字符串
http响应内容包括 字符串和状态码(默认为200)偶尔会需要设置 头部
下面示例返回字符串和状态码

@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400


4.2 直接返回response对象

from flask import make_response
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response



4.3 重定向

重定向经常使用 302 状态码表示,指向的地址由 Location 首部提供。
重定向响应可以使用3 个值形式的返回值生成,也可在 Response 对象中设定。
当然也支持redirect()的内置支持。

from flask import redirect
@app.route('/')
def index():
return redirect('http://www.example.com')



4.4 抛出错误给服务器
from flask import abort
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>Hello, % s</h1>' % user.name



注意, abort 不会把控制权交还给调用它的函数,而是抛出异常把控制权交给 Web 服
务器。

5. flask扩展

Flask 被设计为可扩展形式,故而没有提供一些重要的功能,例如数据库和用户认证,所
以开发者可以自由选择最适合程序的包,或者按需求自行开发。

5.1 Flask-Script 支持命令行选项


示例
from flask.ext.script import Manager
manager = Manager(app)
# ...
if __name__ == '__main__':
manager.run()

(venv) $ python hello.py runserver --help
usage: hello.py runserver [-h] [-t HOST] [-p PORT] [--threaded]
[--processes PROCESSES] [--passthrough-errors] [-d]
[-r]



例如设定运行本地ip:
(venv) $ python hello.py runserver --host 0.0.0.0
* Running on http://0.0.0.0:5000/
* Restarting with reloader




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值