本文整理汇总了Python中tornado.wsgi.WSGIContainer类的典型用法代码示例。如果您正苦于以下问题:Python WSGIContainer类的具体用法?Python WSGIContainer怎么用?Python WSGIContainer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WSGIContainer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tornado
def tornado(port):
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
app = create_app()
wsgi_container = WSGIContainer(app)
wsgi_container._log = lambda *args, **kwargs: None
http_server = HTTPServer(wsgi_container)
http_server.listen(port)
IOLoop.instance().start()
示例2: tornado
def tornado(port):
from tornado.web import Application, FallbackHandler
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
app = flask.current_app
wsgi_container = WSGIContainer(app)
wsgi_container._log = lambda *args, **kwargs: None
handlers = [('.*', FallbackHandler, {'fallback': wsgi_container})]
tornado_app = Application(handlers, debug=app.debug)
http_server = HTTPServer(tornado_app)
http_server.listen(port)
log.info("Hambar109 Tornado listening on port %r", port)
IOLoop.instance().start()
示例3: get
def get(self, *args, **kwargs):
# type: (*Any, **Any) -> None
environ = WSGIContainer.environ(self.request)
environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO'])
request = WSGIRequest(environ)
request._tornado_handler = self
set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
response = self.get_response(request)
if not response:
return
finally:
signals.request_finished.send(sender=self.__class__)
self.set_status(response.status_code)
for h in response.items():
self.set_header(h[0], h[1])
if not hasattr(self, "_new_cookies"):
self._new_cookies = [] # type: List[http.cookie.SimpleCookie]
self._new_cookies.append(response.cookies)
self.write(response.content)
self.finish()
示例4: __init__
def __init__(self, tornado_req, site_conf):
super(TornadoRequest, self).__init__(
WSGIContainer.environ(tornado_req)
)
self._native_request = tornado_req
self.site = site_conf
示例5: get
def get(self):
from tornado.wsgi import WSGIContainer
from django.core.handlers.wsgi import WSGIRequest, get_script_name
import urllib
environ = WSGIContainer.environ(self.request)
environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
request = WSGIRequest(environ)
request._tornado_handler = self
set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
response = self.get_response(request)
if not response:
return
finally:
signals.request_finished.send(sender=self.__class__)
self.set_status(response.status_code)
for h in response.items():
self.set_header(h[0], h[1])
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
self._new_cookies.append(response.cookies)
self.write(response.content)
self.finish()
示例6: get_django_request
def get_django_request(self):
request = \
WSGIRequest(WSGIContainer.environ(self.request))
request.session = self.get_django_session()
if self.current_user:
request.user = self.current_user
else:
request.user = auth.models.AnonymousUser()
return request
示例7: __call__
def __call__(self, request):
data = {}
response = []
def start_response(status, response_headers, exc_info=None):
data["status"] = status
data["headers"] = response_headers
return response.append
app_response = self.wsgi_app(
WSGIContainer.environ(request), start_response)
try:
response.extend(app_response)
body = b"".join(response)
finally:
if hasattr(app_response, "close"):
app_response.close()
if not data:
raise Exception("WSGI app did not call start_response")
status_code, reason = data["status"].split(' ', 1)
status_code = int(status_code)
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = escape.utf8(body)
if HEAD_END in body:
body = body.replace(HEAD_END, self.script + HEAD_END)
if status_code != 304:
if "content-type" not in header_set:
headers.append((
"Content-Type",
"application/octet-stream; charset=UTF-8"
))
if "content-length" not in header_set:
headers.append(("Content-Length", str(len(body))))
if "server" not in header_set:
headers.append(("Server", "LiveServer"))
start_line = httputil.ResponseStartLine(
"HTTP/1.1", status_code, reason
)
header_obj = httputil.HTTPHeaders()
for key, value in headers:
if key.lower() == 'content-length':
value = str(len(body))
header_obj.add(key, value)
request.connection.write_headers(start_line, header_obj, chunk=body)
request.connection.finish()
self._log(status_code, request)
示例8: __call__
def __call__(self, request):
data = {}
response = []
def start_response(status, response_headers, exc_info=None):
data["status"] = status
data["headers"] = response_headers
return response.append
app_response = self.wsgi_application(
WSGIContainer.environ(request), start_response)
try:
response.extend(app_response)
body = b"".join(response)
finally:
if hasattr(app_response, "close"):
app_response.close()
if not data:
raise Exception("WSGI app did not call start_response")
status_code = int(data["status"].split()[0])
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = escape.utf8(body)
body = body.replace(
b'</head>',
b'<script src="/livereload.js"></script></head>'
)
if status_code != 304:
if "content-length" not in header_set:
headers.append(("Content-Length", str(len(body))))
if "content-type" not in header_set:
headers.append(("Content-Type", "text/html; charset=UTF-8"))
if "server" not in header_set:
headers.append(("Server", "livereload-tornado"))
parts = [escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
for key, value in headers:
if key.lower() == 'content-length':
value = str(len(body))
parts.append(
escape.utf8(key) + b": " + escape.utf8(value) + b"\r\n"
)
parts.append(b"\r\n")
parts.append(body)
request.write(b"".join(parts))
request.finish()
self._log(status_code, request)
示例9: get
def get(self):
from tornado.wsgi import HTTPRequest, WSGIContainer
from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
import urllib
environ = WSGIContainer.environ(self.request)
environ["PATH_INFO"] = urllib.unquote(environ["PATH_INFO"])
request = WSGIRequest(environ)
request._tornado_handler = self
set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
response = self.get_response(request)
if not response:
return
# Apply response middleware
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
finally:
signals.request_finished.send(sender=self.__class__)
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = "UNKNOWN STATUS CODE"
status = "%s %s" % (response.status_code, status_text)
self.set_status(response.status_code)
for h in response.items():
self.set_header(h[0], h[1])
"""
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
self._new_cookies.append(response.cookies)
"""
# Tornado 2.3 has changed the _new_cookies methods. Its not an array.
# revert back to old method
for c in response.cookies.values():
self.set_header("Set-Cookie", str(c.output(header="")))
self.write(response.content)
self.finish()
示例10: get
def get(self) :
from tornado.wsgi import HTTPRequest, WSGIContainer
from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
import urllib
environ = WSGIContainer.environ(self.request)
environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
request = WSGIRequest(environ)
request._tornado_handler = self
set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
response = self.get_response(request)
if not response :
return
# Apply response middleware
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
finally:
signals.request_finished.send(sender=self.__class__)
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = 'UNKNOWN STATUS CODE'
status = '%s %s' % (response.status_code, status_text)
self.set_status(response.status_code)
for h in response.items() :
self.set_header(h[0], h[1])
for c in response.cookies.values():
self.set_header('Set-Cookie', str(c.output(header='')))
"""
if hasattr(self, "_new_cookies"):
print self._new_cookies
self._new_cookies = response.cookies
"""
self.write(response.content)
self.finish()
示例11: __call__
def __call__(self, request):
parts = []
parts_append = parts.append
base_header = strftime('\r\nDate: %a, %d %b %Y %H:%M:%S GMT', gmtime()) + '\r\nServer: tornado\r\n'
if not request.supports_http_1_1():
if request.headers.get('Connection', '').lower() == 'keep-alive':
base_header += 'Connection: Keep-Alive\r\n'
def start_response(status, response_headers, exc_info=None):
parts_append(utf8('HTTP/1.1 ' + status + base_header))
for key, value in response_headers:
parts_append(utf8(key + ': ' + value + '\r\n'))
parts_append(self.new_line)
return None
environ = WSGIContainer.environ(request)
environ['wsgi.multiprocess'] = False # Some EvalException middleware fails if set to True
app_response = self.wsgi_application(environ, start_response)
if not parts:
raise Exception('WSGI app did not call start_response')
if request.method != 'HEAD':
parts.extend(app_response)
if hasattr(app_response, 'close'):
app_response.close()
app_response = None
if hasattr(request, "connection"):
# Now that the request is finished, clear the callback we
# set on the IOStream (which would otherwise prevent the
# garbage collection of the RequestHandler when there
# are keepalive connections)
request.connection.stream.set_close_callback(None)
request.write(self.empty_string.join(parts))
try:
request.finish()
except IOError as e:
self.logger.error('Exception when writing response: %s', str(e))
示例12: runCouchPotato
#.........这里部分代码省略.........
except:
version_control(db, repo, version = latest_db_version)
current_db_version = db_version(db, repo)
if current_db_version < latest_db_version:
if development:
log.error('There is a database migration ready, but you are running development mode, so it won\'t be used. If you see this, you are stupid. Please disable development mode.')
else:
log.info('Doing database upgrade. From %d to %d', (current_db_version, latest_db_version))
upgrade(db, repo)
# Configure Database
from couchpotato.core.settings.model import setup
setup()
# Fill database with needed stuff
if not db_exists:
fireEvent('app.initialize', in_order = True)
# Create app
from couchpotato import app
api_key = Env.setting('api_key')
url_base = '/' + Env.setting('url_base').lstrip('/') if Env.setting('url_base') else ''
# Basic config
app.secret_key = api_key
host = Env.setting('host', default = '0.0.0.0')
# app.debug = development
config = {
'use_reloader': reloader,
'port': tryInt(Env.setting('port', default = 5000)),
'host': host if host and len(host) > 0 else '0.0.0.0',
'ssl_cert': Env.setting('ssl_cert', default = None),
'ssl_key': Env.setting('ssl_key', default = None),
}
# Static path
app.static_folder = os.path.join(base_path, 'couchpotato', 'static')
web.add_url_rule('api/%s/static/<path:filename>' % api_key,
endpoint = 'static',
view_func = app.send_static_file)
# Register modules
app.register_blueprint(web, url_prefix = '%s/' % url_base)
app.register_blueprint(api, url_prefix = '%s/api/%s/' % (url_base, api_key))
# Some logging and fire load event
try: log.info('Starting server on port %(port)s', config)
except: pass
fireEventAsync('app.load')
# Go go go!
from tornado.ioloop import IOLoop
web_container = WSGIContainer(app)
web_container._log = _log
loop = IOLoop.current()
application = Application([
(r'%s/api/%s/nonblock/(.*)/' % (url_base, api_key), NonBlockHandler),
(r'.*', FallbackHandler, dict(fallback = web_container)),
],
log_function = lambda x : None,
debug = config['use_reloader'],
gzip = True,
)
if config['ssl_cert'] and config['ssl_key']:
server = HTTPServer(application, no_keep_alive = True, ssl_options = {
"certfile": config['ssl_cert'],
"keyfile": config['ssl_key'],
})
else:
server = HTTPServer(application, no_keep_alive = True)
try_restart = True
restart_tries = 5
while try_restart:
try:
server.listen(config['port'], config['host'])
loop.start()
except Exception, e:
try:
nr, msg = e
if nr == 48:
log.info('Already in use, try %s more time after few seconds', restart_tries)
time.sleep(1)
restart_tries -= 1
if restart_tries > 0:
continue
else:
return
except:
pass
raise
try_restart = False
示例13: wrapper
def wrapper(request, response):
req = yield request.read()
for data in application(WSGIContainer.environ(req), functools.partial(start_response, response)):
response.write(data)
response.close()
示例14: __call__
def __call__(self, request):
data = {}
response = []
def start_response(status, response_headers, exc_info=None):
data["status"] = status
data["headers"] = response_headers
return response.append
app_response = self.wsgi_application(WSGIContainer.environ(request), start_response)
try:
response.extend(app_response)
body = b"".join(response)
finally:
if hasattr(app_response, "close"):
app_response.close()
if not data:
raise Exception("WSGI app did not call start_response")
status_code = int(data["status"].split()[0])
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = escape.utf8(body)
if status_code != 304:
if "content-length" not in header_set:
headers.append(("Content-Length", str(len(body))))
if "content-type" not in header_set:
headers.append(("Content-Type", "text/html; charset=UTF-8"))
if "server" not in header_set:
headers.append(("Server", "TornadoServer/%s" % tornado.version))
# try:
# if request.method.lower() != GET:
# _cookies = Cookie.SimpleCookie()
# Django session cookies are set at the django level, but
# tornado-specific cookies are appended here.
# token = request.cookies[djsettings.CSRF_COOKIE_NAME]
# if token:
# _cookies[settings.XSRF_TOKEN] = token.value
# TODO Change when we add more contexts
# _cookies[settings.CONTEXT_COOKIE] = settings.DEFAULT_CONTEXT
# for c in _cookies.output(sep='\t').split('\t'):
# k, v = c.split(': ')
# headers.append((k, v + '; Path=/'))
# except ValueError as e:
# logging.getLogger("ef5").error("A Value is either missing or invalid: {0}".format(e))
# except Exception as e:
# logging.getLogger("ef5").error("An unknown error occurred: {0} with stacktrace {1}".format(e, traceback.format_exc()))
parts = [escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
for key, value in headers:
parts.append(escape.utf8(key) + b": " + escape.utf8(value) + b"\r\n")
parts.append(b"\r\n")
parts.append(body)
request.write(b"".join(parts))
request.finish()
self._log(status_code, request)
示例15: __init__
def __init__(self, *args, **kwargs):
_RequestHandler.__init__(self, *args, **kwargs)
self.environ = WSGIContainer.environ(self.request)