当前位置: 首页 > news >正文

旅游局网站建设解决方案郑州网络营销顾问

旅游局网站建设解决方案,郑州网络营销顾问,做背景图 网站,网站都需要什么类别在 Python 的 Web 开发框架 flask 中有这样的四个全局变量,我们经常会使用它们来存取数据,在处理请求过程中它们是非常方便的,因为它们的实现方法是相同的,所以这里我们重点探究一下 request 的使用,其它的都是类似的。…

在 Python 的 Web 开发框架 flask 中有这样的四个全局变量,我们经常会使用它们来存取数据,在处理请求过程中它们是非常方便的,因为它们的实现方法是相同的,所以这里我们重点探究一下 request 的使用,其它的都是类似的。下面是 flask.globals 的代码(我删减了一部分):

"""
删减了一部分代码,这里的关注重点是 request 变量。
"""# -*- coding: utf-8 -*-
"""flask.globals
"""from functools import partial
from werkzeug.local import LocalStack, LocalProxy_request_ctx_err_msg = '''\
Working outside of request context.This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.\
'''def _lookup_req_object(name):top = _request_ctx_stack.topif top is None:raise RuntimeError(_request_ctx_err_msg)return getattr(top, name)# context locals
_request_ctx_stack = LocalStack()
_app_ctx_stack = LocalStack()
current_app = LocalProxy(_find_app)
request = LocalProxy(partial(_lookup_req_object, 'request'))
session = LocalProxy(partial(_lookup_req_object, 'session'))
g = LocalProxy(partial(_lookup_app_object, 'g'))

从这里我们可以看到 current_app, request, session, g 的定义是类似的,所以我们这里只探究 request 即可。这几个变量都是全局变量,但是我们在使用时并不需要关心这点,因为框架已经帮我们做好了封装。每个线程或者协程只能访问自己特定的资源,不同线程或线程之间不会互相冲突。

1.1 Local 类

我们直接跳转到 LocalProxy 所在的文件,这个文件里面定义了 Local, LocalStack, LocalProxy 类。

"""
Local 类是 flask 中实现类似于 threadlocal 存储的类,只不过 threadlocal 是绑定了线程,
而它可以绑定线程、协程等,如果理解了前者,对于后者也会很容易掌握的。简单来说,它是一个全局字典,每个线程或者协程会在其中存储它们各自的数据,数据的键是它们
的标识符(唯一性),这样存取数据就不会冲突了,从用户的角度来看一切都是透明的,他们只是从
它里面存取数据,而不用考虑多线程数据的冲突。它只有两个属性:- __storage__
- __ident_func__`__storage__` 是用来存储数据的,`__ident_func__` 是线程或者协程的唯一标识符,用于区分是哪一个具体的线程或者协程。
关于它的具体实现,会使用一些高级的 Python 语法,不过对于我们用户来说知道它的作用即可,具体的实现就超出
理解的范围了,学习一定要有取舍。这里还要关注一下 `__call__` 方法,它会传入当前实例和一个 proxy 参数,创建一个 LocalProxy 实例,这里这个 proxy 是代理的实例的名字。
"""class Local(object):__slots__ = ("__storage__", "__ident_func__")def __init__(self):object.__setattr__(self, "__storage__", {})object.__setattr__(self, "__ident_func__", get_ident)def __iter__(self):return iter(self.__storage__.items())def __call__(self, proxy):"""Create a proxy for a name."""return LocalProxy(self, proxy)def __release_local__(self):self.__storage__.pop(self.__ident_func__(), None)def __getattr__(self, name):try:return self.__storage__[self.__ident_func__()][name]except KeyError:raise AttributeError(name)def __setattr__(self, name, value):ident = self.__ident_func__()storage = self.__storage__try:storage[ident][name] = valueexcept KeyError:storage[ident] = {name: value}def __delattr__(self, name):try:del self.__storage__[self.__ident_func__()][name]except KeyError:raise AttributeError(name)

1.2 LocalStack 类

"""
这个类和 Local 类很相似,不过它是数据是存储在一个栈中的,也就是说值的部分是一个列表,
按照栈的方式进行存取数据。Flask 中也是直接用的 LocalStack 类,而不是 Local 类。
"""class LocalStack(object):"""This class works similar to a :class:`Local` but keeps a stackof objects instead.  This is best explained with an example::>>> ls = LocalStack()>>> ls.push(42)>>> ls.top42>>> ls.push(23)>>> ls.top23>>> ls.pop()23>>> ls.top42They can be force released by using a :class:`LocalManager` or withthe :func:`release_local` function but the correct way is to pop theitem from the stack after using.  When the stack is empty it willno longer be bound to the current context (and as such released).By calling the stack without arguments it returns a proxy that resolves tothe topmost item on the stack... versionadded:: 0.6.1"""def __init__(self):self._local = Local()def __release_local__(self):self._local.__release_local__()def _get__ident_func__(self):return self._local.__ident_func__def _set__ident_func__(self, value):object.__setattr__(self._local, "__ident_func__", value)__ident_func__ = property(_get__ident_func__, _set__ident_func__)del _get__ident_func__, _set__ident_func__def __call__(self):def _lookup():rv = self.topif rv is None:raise RuntimeError("object unbound")return rvreturn LocalProxy(_lookup)def push(self, obj):"""Pushes a new item to the stack"""rv = getattr(self._local, "stack", None)if rv is None:self._local.stack = rv = []rv.append(obj)return rvdef pop(self):"""Removes the topmost item from the stack, will return theold value or `None` if the stack was already empty."""stack = getattr(self._local, "stack", None)if stack is None:return Noneelif len(stack) == 1:release_local(self._local)return stack[-1]else:return stack.pop()@propertydef top(self):"""The topmost item on the stack.  If the stack is empty,`None` is returned."""try:return self._local.stack[-1]except (AttributeError, IndexError):return None

1.3 LocalProxy 类

@implements_bool
class LocalProxy(object):"""Acts as a proxy for a werkzeug local.  Forwards all operations toa proxied object.  The only operations not supported for forwardingare right handed operands and any kind of assignment.Example usage::from werkzeug.local import Locall = Local()# these are proxiesrequest = l('request')user = l('user')from werkzeug.local import LocalStack_response_local = LocalStack()# this is a proxyresponse = _response_local()Whenever something is bound to l.user / l.request the proxy objectswill forward all operations.  If no object is bound a :exc:`RuntimeError`will be raised.To create proxies to :class:`Local` or :class:`LocalStack` objects,call the object as shown above.  If you want to have a proxy to anobject looked up by a function, you can (as of Werkzeug 0.6.1) passa function to the :class:`LocalProxy` constructor::session = LocalProxy(lambda: get_current_request().session)"""__slots__ = ("__local", "__dict__", "__name__", "__wrapped__")def __init__(self, local, name=None):object.__setattr__(self, "_LocalProxy__local", local)object.__setattr__(self, "__name__", name)if callable(local) and not hasattr(local, "__release_local__"):# "local" is a callable that is not an instance of Local or# LocalManager: mark it as a wrapped function.object.__setattr__(self, "__wrapped__", local)

1.4 总结:Local, LocalStack, LocalProxy 的简单使用

为了便于理解它们几个的作用,这里提供一个示例用于演示:

from werkzeug import LocalStack, LocalProxyclass Request:def __init__(self, method: str, url: str, query: str):self.method = methodself.url = urlself.query = querydef __repr__(self):return f'{">"*30}\nmethod: {self.method}\nurl: {self.url}\nquery: {self.query}\n{"<"*30}\n'class RequestContext:def __init__(self, request):    # request 是 RequestContext 的属性self.request = requestdef _lookup_req_object(name):top = request_stack.topif top is None:raise RuntimeError("Working outside of request context.")return getattr(top, name)request_stack = LocalStack()
request = LocalProxy(lambda: _lookup_req_object('request')) # 源码里面是偏函数,这里我用lambda 代替if __name__ == "__main__":# 原始对象测试print("原始对象测试:")req = Request("GET", "/v1/user", {"name": "peter"})req_ctx = RequestContext(req)print("method: ", req.method)print("url: ", req.url)print("query: ", req.query)print("original request", req)print('-'*30)print("代理对象测试:")        # 将 RequestContext 对象推送 LocalStack 实例中,request_stack.push(req_ctx)   # 然后我们直接访问 request 对象(代理对象)print("method: ", request.method)print("url: ", request.url)print("query: ", request.query)print("request: ", request)print("proxied object: \n", request._get_current_object())target_func = lambda r: print(r.method)# 在当前线程中访问全局 request 对象print("*"*30)target_func(request)print("*"*30)# 尝试在另一个线程中访问全局 request 对象,guess what will happen?from threading import Threadt = Thread(target=target_func, args=(request,))t.start()t.join()

Copy and Paste the demo code, Run it, try it out!

当尝试在当前线程之外访问 request 中的内容,将会导致一个运行时异常,因为 request 是绑定到特定线程或者协程的,如果使用一个新的线程或者协程,它在全局 request_stack 中是没有数据的,因此会异常。所以一定要注意,不要在变量的上下文范围之外去读写数据,除非手动推入数据。

在这里插入图片描述

http://www.cadmedia.cn/news/11147.html

相关文章:

  • 怎样建网站最快关键词搜索量排名
  • 有没有做二手设备网站软文新闻发稿平台
  • wordpress登录可见代码西安排名seo公司
  • 潍坊专业网站建设多少钱如何推广app赚钱
  • 番禺商城网站建设互联网营销的五个手段
  • 企业建立企业网站有哪些优势?指数
  • wordpress3.7哈尔滨百度搜索排名优化
  • 建设银行网站怎么修改手机号码新闻软文发布平台
  • 教你如何做外挂的网站色盲测试图看图技巧
  • 扬中最近最新事件seo广告优化多少钱
  • 宝华路桥建设集团网站新浪微指数
  • 南京广告制作公司百度关键词优化
  • 合肥网站建设企业免费网站安全软件大全游戏
  • 彩票网站搭建多钱seo搜索引擎优化视频
  • 郑州网站建设郑州网站建设七彩科技天津seo外包
  • 网站建设进度表模板下载南昌seo实用技巧
  • 如何制作手机app应用软件做网站seo推广公司
  • 金乡县住房与城乡建设局网站深圳广告策划公司
  • 郑州网站建设公司哪家专业电商平台引流推广
  • 广州建设工程质量安全网站什么是口碑营销
  • 要建一个网站该怎么做seo 适合哪些行业
  • 网页制作培训机构好不好seo排名工具提升流量
  • 中国建设网官方网址湖南专业seo公司
  • 网站建设需要哪些条件百度竞价排名收费
  • 果洛电子商务网站建设哪家好快速排名教程
  • 网站建设备案不通过网页设计与制作考试试题及答案
  • 怎么制造网站引流推广效果好的app
  • 丹阳做网站恩城seo的网站
  • 山东已经宣布封城的城市如何做seo
  • 免费建网站哪个网好电商怎么做如何从零开始