如何从控制台中的龙卷风中的处理程序登录?我从控制台启动了应用程序并将其放在处理程序之上logging.getLogger().setLevel(logging.DEBUG)
和内部处理程序
logging.info('RECEIVED HTTP GET REQUEST')
Run Code Online (Sandbox Code Playgroud)
但是处理程序没有在控制台中写入任何内容。我试过打印,但它在处理程序中不起作用。
我用它来设置我的日志,但没有用。
tornado.options.options['log_file_prefix'].set('/opt/logs/my_app.log')
tornado.options.parse_command_line()
Run Code Online (Sandbox Code Playgroud)
得到这个错误
tornado.options.options['log_file_prefix'].set('/logs/my_app.log')
TypeError: 'OptionParser' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
我希望将日志打印在终端和日志文件上,并且我通过 xml 配置文件而不是直接通过命令行启动我的应用程序,我该怎么做?
我有一个基于异步 Tornado 和 mongoDB 的 API。它工作正常,除了一个处理程序:
@gen.coroutine
def get(self, *args, **kwargs):
"""
Gets tracking lib
"""
data = self._get_request_data()
self._serialize_request_data(AuthValidator, data)
tags = yield self.motor.tags.find_one({"client_id": data["client_id"]})
raise Return(self.write(tags))
Run Code Online (Sandbox Code Playgroud)
当请求到来时,tornado 返回带有以下堆栈跟踪的 HTTP 500:
response: Traceback (most recent call last):
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/web.py", line 1334, in _execute
result = yield result
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 617, in run
value = future.result()
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 620, in run
yielded = self.gen.throw(*sys.exc_info())
File "/Users/artemkorhov/Projects/cartreminder/cartreminder_app/tracking_api/api_handlers/endpoints.py", line 35, in get
tags …Run Code Online (Sandbox Code Playgroud) 我正在使用 python 发送多个 HTTP 请求 .. > 1000 个请求同时被异步触发。但我收到错误:达到 max_clients 限制,请求排队龙卷风,过了一会儿我收到超时错误。
你如何解决这种问题,发送多个http post请求并避免超时?
这是我正在使用的代码:
class AjaxBatchHandler(basehandler.BaseHandler):
@tornado.gen.coroutine
def post(self):
# just respond with a status, no redirect to login
if not self.get_current_user:
self.set_status(403)
batch = json.loads(self.get_argument("actions").encode('utf-8'))
client = tornado.httpclient.AsyncHTTPClient()
batch_requests = []
for item in batch['actions']:
request = utils.build_request(
self,
action=item['action'].replace("{API}", utils.get_api_baseurl()),
values=item['values'])
batch_requests.append(client.fetch(request))
try:
batch_responses = yield batch_requests
batch_result = dict(results=[])
for result in batch_responses:
batch_result['results'].append(json.loads(result.body))
except tornado.httpclient.HTTPError as e:
batch_result = dict(results=[])
batch_result['results'].append({"Status": 500,
"StatusMsg": e.message, …Run Code Online (Sandbox Code Playgroud) 我想向我的 Web 应用程序的用户显示错误。在处理请求时,我可能会提出HTTPError这样的问题:
raise tornado.web.HTTPError(403, reason="You're not authorised")
Run Code Online (Sandbox Code Playgroud)
在我的开发环境中运行它时,会产生如下响应状态:
403 You're not authorised
Run Code Online (Sandbox Code Playgroud)
但是当我在生产中运行它时,我得到:
403 Forbidden
Run Code Online (Sandbox Code Playgroud)
更改serve_traceback和debug选项无济于事:在响应正文中返回回溯,但状态消息仍然只是“禁止”。
为什么它在生产中返回错误消息?
龙卷风 4.1
我的网站是 http 协议。我的flask API 通过flask-httpauth ( https://github.com/miguelgrinberg/Flask-HTTPAuth ) 得到保护。
在我的 Flask API 前面有一个 Tornado Web 服务器,它侦听私有端口 5000。客户端 API 请求首先转到 Tornado 服务器,然后它调用 Flask API
这是我要去的流程:
我的网站(在 http 上)---> corpauthentication(在 https 上)--> 回到我的网站(http)--> 客户端调用 Tornado 服务器 --> Tornado 调用 Flask API 并返回结果
我的 API 和网站的安全性如何?我正在阅读此链接Security of python flask REST API using HTTP Basic Authentication,在我看来该 API 是安全的,但我永远无法确定。
如果它不安全,你认为我还能做些什么来使它更安全?由于需要进行公司验证才能进入,我觉得在 UI 方面它非常安全。但是假设有人正在监听我的 80 端口,即使存在 tornado + httpbasic 身份验证,他们是否能够跟踪任何 API 请求?
这是我的 Tornado 服务器代码:
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web …Run Code Online (Sandbox Code Playgroud) 我从这个 Tornado文档中使用生产者和消费者修改了示例队列,但传递给 get() 的超时参数似乎根本不起作用,因为消费者在抛出异常之前不会等待 10 秒。理想情况下,生产者和消费者将同时运行。另外,我不知道是将超时参数作为秒还是毫秒传递:
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import Queue
q = Queue()
@gen.coroutine
def consumer():
try:
while True:
item = yield q.get(timeout=10000)
try:
print('Doing work on %s' % item)
finally:
q.task_done()
except gen.TimeoutError:
print('timeout')
return
@gen.coroutine
def producer():
for item in range(5):
yield q.put(item)
print('Put %s' % item)
yield gen.sleep(2)
@gen.coroutine
def main():
# Start consumer without waiting (since it never finishes).
IOLoop.current().spawn_callback(consumer)
yield producer() # Wait for producer …Run Code Online (Sandbox Code Playgroud) 我正在从 Tornado 理解协程,所以让我们保持一切简单,粘贴的代码越多越好。
我想要的是让我自制的函数异步。
我可以在文档中找到的所有示例都属于同一个“隐藏”部分:AsyncHTTPClient。我不打算进行 HTTP 调用。所以请不要给我举那个班级的例子。我有兴趣从头开始创造一些东西。我已经尝试了Tornado 协程的所有可能性
现在我一直在用 bash sleep 进行测试。这是代码:
import tornado.web
import tornado.httpserver
import tornado.gen
import tornado.concurrent
import subprocess
import os
@tornado.gen.coroutine
def letswait():
fut = tornado.concurrent.Future()
subprocess.check_output(["sleep", "5"])
fut.set_result(42)
return fut
class TestHandler1(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
value = yield letswait()
self.render("test.html", num=value)
class TestHandler2(tornado.web.RequestHandler):
def get(self):
self.render("test.html", num=66)
class Application(tornado.web.Application):
def __init__(self):
DIRNAME = os.path.dirname(__file__)
STATIC_PATH = os.path.join(DIRNAME, '../static')
TEMPLATE_PATH = os.path.join(DIRNAME, '../template')
sets = {
"template_path":TEMPLATE_PATH,
"static_path":STATIC_PATH,
"debug":True,
}
tornado.web.Application.__init__(self, [
(r"/test1", TestHandler1), …Run Code Online (Sandbox Code Playgroud) 我想将 json 文件呈现为 html 脚本部分。在龙卷风部分,No1 正在将 json 数据发送到 html。并且,No2 部分接收来自 No1 的 json 数据。但是,此代码不起作用。我发现 html 脚本不允许 {{ }} 的形式。我如何将 json 数据发送到 html 的一部分?
[python-龙卷风部分]
import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=data) #No1
def main():
tornado.options.parse_command_line() …Run Code Online (Sandbox Code Playgroud) 我在单个 AWS 实例上运行服务器(使用 Tornado python),并且我遇到了 websocket 延迟的峰值。
分析从 websocket 消息发送到客户端的往返时间,然后客户端立即将 ack 消息发送回服务器,到服务器收到 ack 消息时平均产生 <.1 秒,但是我有时注意到它最多 3 秒。注意:在本地运行服务器时没有峰值。
这可能是什么原因或解决方法?我查看了 CPU 使用率,最多只能达到 40%。峰值与高流量(通常是 2 或 3 个客户端)无关,并且客户端的互联网似乎很好。我发现很难相信实例会以如此低的使用率超出容量。
tornado ×10
python ×7
api ×1
asynchronous ×1
flask ×1
haproxy ×1
html ×1
http ×1
javascript ×1
json ×1
mongodb ×1
pymongo ×1
python-2.7 ×1
python-3.x ×1
queue ×1
websocket ×1