flask 导入的模块

from __future__ import with_statement
import os
import sysfrom threading import local
from jinja2 import Environment, PackageLoader, FileSystemLoader
from werkzeug import Request as RequestBase, Response as ResponseBase, \LocalStack, LocalProxy, create_environ, cached_property, \SharedDataMiddleware
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, InternalServerError
from werkzeug.contrib.securecookie import SecureCookie# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug import abort, redirect
from jinja2 import Markup, escape# use pkg_resource if that works, otherwise fall back to cwd.  The
# current working directory is generally not reliable with the notable
# exception of google appengine.
try:import pkg_resourcespkg_resources.resource_stream
except (ImportError, AttributeError):pkg_resources = None

1.class Request增加了endpointview_args两个参数,用来接收reuqest的url,父类在werkzeug中实现,用来包装environ,方便我们操作

class Request(RequestBase): # 这里的RequestBase是werkzeug定义的def __init__(self, environ):RequestBase.__init__(self, environ) # 直接写父类的名称`RequestBase`不推荐,最好用super()代替self.endpoint = Noneself.view_args = None

2.class Response增加了返回的默认的mimetype类型

class Response(ResponseBase):default_mimetype = 'text/html'

3.class _RequestGlobals

4.class _RequestContext 包含了所有请求的信息
请求进来时被创建,然后加入_request_ctx_stack,请求结束时删除.

class _RequestContext(object): # 使用with语句,拿到栈顶的request进行处理def __init__(self, app, environ):self.app = app # 当前的appself.url_adapter = app.url_map.bind_to_environ(environ) # 主要用来处理URL,因为绑定了environ以后就不需要再往match里传递参数了self.request = app.request_class(environ) # 当前的请求信息self.session = app.open_session(self.request) # 当前的会话信息self.g = _RequestGlobals() # ?self.flashes = Nonedef __enter__(self): # 使用with语句_request_ctx_stack.push(self) # 将当前请求推入栈def __exit__(self, exc_type, exc_value, tb):# do not pop the request stack if we are in debug mode and an# exception happened.  This will allow the debugger to still# access the request object in the interactive shell.if tb is None or not self.app.debug:_request_ctx_stack.pop() # 将往前请求推出栈

5.def url_forendpoint(url的id,一般就是视图函数),

def url_for(endpoint, **values):return _request_ctx_stack.top.url_adapter.build(endpoint, values)

6.def flash(message),发送一个message到下一个请求中

def flash(message):session['_flashes'] = (session.get('_flashes', [])) + [message

7.def get_flashed_messages

def get_flashed_messages():"""Pulls all flashed messages from the session and returns them.Further calls in the same request to the function will returnthe same messages."""flashes = _request_ctx_stack.top.flashesif flashes is None:_request_ctx_stack.top.flashes = flashes = \session.pop('_flashes', [])return flashes

8.def render_template

def render_template(template_name, **context):"""Renders a template from the template folder with the givencontext.:param template_name: the name of the template to be rendered:param context: the variables that should be available in thecontext of the template."""current_app.update_template_context(context)return current_app.jinja_env.get_template(template_name).render(context

9.def render_template_string

def render_template_string(source, **context):"""Renders a template from the given template source stringwith the given context.:param template_name: the sourcecode of the template to berendered:param context: the variables that should be available in thecontext of the template."""current_app.update_template_context(context)return current_app.jinja_env.from_string(source).render(context

10.def _default_template_ctx_processor


def _default_template_ctx_processor():"""Default template context processor.  Injects `request`,`session` and `g`."""reqctx = _request_ctx_stack.topreturn dict(request=reqctx.request,session=reqctx.session,g=reqctx.g)

11.def _get_package_path(name)
获得app模块的路径app = Flask(__name__),默认都是使用__main__

def _get_package_path(name):"""Returns the path to a package or cwd if that cannot be found."""try:return os.path.abspath(os.path.dirname(sys.modules[name].__file__))except (KeyError, AttributeError):return os.getcwd()

12.class Flask

class Flask(object):request_class = Requestresponse_class = Responsestatic_path = '/static' # path for the static filessecret_key = None # cryptographic components can use this to sign cookies and other thingssession_cookie_name = 'session' # name of the session cookiejinja_options = dict(  # jinja2 的配置autoescape=True,extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'])def __init__(self, package_name): # `app = Flask(__name__)`self.debug = Falseself.package_name = package_nameself.root_path = _get_package_path(self.package_name) #: where is the app root located?self.view_functions = {} # a dictionary of all view functions registered(`route` decorator)self.error_handlers = {} # a dictionary of all registered error handlers,`errorhandler`decoratorself.before_request_funcs = [] # a list of functions that should be called at the beginning f the requestself.after_request_funcs = [] # a list of functions that are called at the end of the request.self.template_context_processors = [_default_template_ctx_processor] #: to populate the template context.self.url_map = Map()if self.static_path is not None: # 若果静态文件存在,则通过ShareDatMiddleware设置静态文件夹self.url_map.add(Rule(self.static_path + '/<filename>',build_only=True, endpoint='static')) # 添加静态文件urlif pkg_resources is not None: # 如果是package不是主程序的话,要从包的路径找`static`target = (self.package_name, 'static')else:target = os.path.join(self.root_path, 'static') # 如果是主程序则拼贴`static`的路径self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {self.static_path: target})self.jinja_env = Environment(loader=self.create_jinja_loader(),**self.jinja_options) # 配置jinjia2self.jinja_env.globals.update(url_for=url_for,get_flashed_messages=get_flashed_messages)def create_jinja_loader(self): # 添加jinja2的载入,默认是`templates`if pkg_resources is None:return FileSystemLoader(os.path.join(self.root_path, 'templates'))return PackageLoader(self.package_name)def update_template_context(self, context): #更新template 上下文reqctx = _request_ctx_stack.topfor func in self.template_context_processors:context.update(func())def run(self, host='localhost', port=5000, **options):from werkzeug import run_simpleif 'debug' in options:self.debug = options.pop('debug')options.setdefault('use_reloader', self.debug)options.setdefault('use_debugger', self.debug)return run_simple(host, port, self, **options)def test_client(self): # 创建一个客户端,主要用来测试from werkzeug import Clientreturn Client(self, self.response_class, use_cookies=True)def open_resource(self, resource): # 打开一个源文件,主要是用来测试if pkg_resources is None:return open(os.path.join(self.root_path, resource), 'rb')return pkg_resources.resource_stream(self.package_name, resource)def open_session(self, request): # 会话,通过cookie来实现key = self.secret_keyif key is not None:return SecureCookie.load_cookie(request, self.session_cookie_name,secret_key=key)def save_session(self, session, response):if session is not None:session.save_cookie(response, self.session_cookie_name)# 处理请求def add_url_rule(self, rule, endpoint, **options): # 添加URL_RULEoptions['endpoint'] = endpointoptions.setdefault('methods', ('GET',))self.url_map.add(Rule(rule, **options))def route(self, rule, **options): # 路由处理def decorator(f):self.add_url_rule(rule, f.__name__, **options) # 给url起名字self.view_functions[f.__name__] = f # 给view_function起相同的名字return freturn decoratordef errorhandler(self, code):def decorator(f):self.error_handlers[code] = freturn freturn decoratordef before_request(self, f):self.before_request_funcs.append(f)return fdef after_request(self, f):self.after_request_funcs.append(f)return fdef context_processor(self, f): # 添加context_processorsself.template_context_processors.append(f)return fdef match_request(self):rv = _request_ctx_stack.top.url_adapter.match() # 通过调用rule.match(path, method))从而返回rule的endpointrequest.endpoint, request.view_args = rv # 将值赋值给request,request是代买最下面的localproxyreturn rvdef dispatch_request(self):try:endpoint, values = self.match_request() # 根据url获得endpoint和valuesreturn self.view_functions[endpoint](**values) # 调用相应的方法except HTTPException, e: # 如果错误则传入handlerhandler = self.error_handlers.get(e.code)if handler is None:return ereturn handler(e)except Exception, e:handler = self.error_handlers.get(500)if self.debug or handler is None:raisereturn handler(e)def make_response(self, rv): # 返回内容if isinstance(rv, self.response_class):return rvif isinstance(rv, basestring):return self.response_class(rv)if isinstance(rv, tuple):return self.response_class(*rv)return self.response_class.force_type(rv, request.environ)def preprocess_request(self): # 对请求进行预处理,如果最后rv不为空,则返回(有可能经过预处理rv就没了,比如说拦截)for func in self.before_request_funcs: # 调用预处理函数,是个列表 before_request_funcsrv = func()if rv is not None:return rvdef process_response(self, response):session = _request_ctx_stack.top.sessionif session is not None:self.save_session(session, response)for handler in self.after_request_funcs:response = handler(response)return responsedef wsgi_app(self, environ, start_response): # 真实的WSGI application,在__call__中调用with self.request_context(environ):rv = self.preprocess_request() # 首先调用预处理请求函数if rv is None: # 如果预处理后,返回为None,??rv = self.dispatch_request() # 这时可能返回字符串,也可能是responseclassresponse = self.make_response(rv) # 进一步处理,比如如果是response = self.process_response(response) # 保存sessionreturn response(environ, start_response)def request_context(self, environ):return _RequestContext(self, environ)def test_request_context(self, *args, **kwargs):return self.request_context(create_environ(*args, **kwargs))def __call__(self, environ, start_response):return self.wsgi_app(environ, start_response)
# context locals
_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)
session = LocalProxy(lambda: _request_ctx_stack.top.session)
g = LocalProxy(lambda: _request_ctx_stack.top.g)

flask v0.1 flask.py相关推荐

  1. Flask之解读app.py文件

    从flask包中导入Flask类 Flask这个类是项目的核心,以后很多操作都基于这个类的对象 注册url.注册蓝图等都是基于这个类的对象 from flask import Flask 创建一个Fl ...

  2. python flask安装_python flask安装和命令详解

    Flask Web开发实战学习笔记 Flask简介 Flask是使用Python编写的Web微框架.Web框架可以让我们不用关 心底层的请求响应处理,更方便高效地编写Web程序.因为Flask核心简 ...

  3. flask redis_在Flask应用程序中将Redis队列用于异步任务

    flask redis By: Content by Edward Krueger and Josh Farmer, and Douglas Franklin. 作者: 爱德华·克鲁格 ( Edwar ...

  4. flask 模板 php,Flask 模板系统

    模板 基本数据类型 可以执行python语法,如:dict.get(), list['xx'] 比django 更加亲近于 python 传入函数 - django,自动执行 - flask,不自动执 ...

  5. Flask——1.初识flask微框架

    官网:http://python.usyiyi.cn/translate/flask_011_ch/index.html 1. FLASK 概述 Flask是使用python语言编写的一个轻量级的we ...

  6. 我爱Flask框架之Flask简介与URL和视图介绍

    一:虚拟环境介绍 黄色部分重点注意 虚拟环境与全局环境: 我们通过pip安装了一个python库,可能在编辑器中不能使用(如:pycharm,vscode-)这是因为: 通过pip安装的库默认一般安装 ...

  7. pycharm专业版创建flask项目|下载flask包|以及一些例子

    file–>new project–>flask–>create 在pycharm中下载flask包. 我使用第一种方法一直失败,所以我选了第二种方法,最终成功安装flask包. 第 ...

  8. python安装flask模块_python Flask模块部署

    python Flask模块部署 简介 python Flask作为python中的一个微框架,它提供了一个web应用后端处理的框架,通过Flask中封装好的api来进行网页的渲染.及定制api的实现 ...

  9. 【Flask教程】Flask开发基础与入门

    一.Flask中的Hello World from flask import Flask app = Flask(__name__) @app.route('/') //路由 def hello_wo ...

最新文章

  1. 同意按钮,倒计时10秒,同意按钮变为可提交的
  2. mysql执行一条语句会加锁吗_一条简单的更新语句,MySQL是如何加锁的?
  3. 深入分析glibc内存释放时的死锁bug
  4. c++解析csv 存入数组_Python读写csv文件专题教程(2)
  5. Docker、Kubernetes与PaaS不得不说的渊源
  6. 法学界四大主流“数据权利与权属”观点
  7. 最大似然估计与最小二乘
  8. 【配送路径规划】基于matlab遗传算法求解单配送中心多客户多车辆最短路径规划问题【含Matlab源码 1602期】
  9. postman 生成html测试报告
  10. 51单片机c语言开发工具keil安装
  11. 深度学习 - 生成对抗网络
  12. CSS3相比CSS新增哪些功能
  13. bitbake 编译错误集
  14. webMethods入门简介
  15. linux进程中monitor,linux进程监控,monitor脚本
  16. 考拉nbsp;PASCALnbsp;解题报告
  17. LeetCode: 868. Binary Gap
  18. 计算机组装与维护双系统安装,给你的电脑安装一个不可见的WINPE救援系统(独立启动双系统)...
  19. Oracle Golden Gate 系列七 -- 配置 GG Manager process
  20. 5G对广播电视的影响以及应用-论文

热门文章

  1. android 模仿微信布局,【Android初学者】框架布局:仿微信页面制作
  2. atomic原子类实现机制_反射机制实现两个类的复制
  3. 使用Python模拟蒙蒂霍尔悖论游戏
  4. Python花式编程案例集锦(6)
  5. Python编写抽奖式随机提问程序
  6. c语言lr分析器的设计与实现_[源码和文档分享]基于有限自动机的词法分析器构造...
  7. 1.(单选题) HTML是指,《计算机应用基础》第五阶段在线作业(自测).doc
  8. java获取窗口_如何使用Java获取当前打开的窗口/进程的列表?
  9. jupyter notebook保存的文件在哪_通过配置文件修改jupyter notebook初始文件夹
  10. C++之临时对象、常引用和浅拷贝探究