Python: ConnectionResetError при выполнении HTTP-запросов через Starlette

Я создаю Starlette API, который может выгружать данные в NSQ через HTTP-запрос.

from starlette.applications import Starlette
from starlette.requests     import Request
from starlette.responses    import JSONResponse
from starlette.responses    import RedirectResponse
import uvicorn

import requests
import logging

app = Starlette( debug= True )

NSQ_HTTP_WRITER = [ "localhost:4150" ]


@app.route( "/dump_to_nsq", methods= [ "POST" ] )
async def dump_to_nsq( request ):
    data = await request.json()
    item = data[ "item" ]

    json_object       = { "item": item }

    nsq_dump = requests.post( "http://%s/pub" % ( NSQ_HTTP_WRITER[ 0 ] ), params= { "topic": "nsq_topic" }, data= json_object )

    if nsq_dump.status_code == 200:
        return JSONResponse( { "status": True } )
    else:
        return JSONResponse( { "status": False } )

if __name__ == "__main__":
    uvicorn.run( app, host= "0.0.0.0", port= 8000 )

Когда я пытаюсь запустить это, я получаю сообщение об ошибке:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

Насколько я понимаю, вы не можете отправить requestsэлемент внутри сервера. Я столкнулся с той же проблемой и с Торнадо. Как это решить? Как я могу отправить HTTP-запрос на отправку с сервера Starlette?

Вот полная трассировка ошибок:

ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
File "/usr/local/lib/python3.7/site-packages/starlette/applications.py", line 134, in __call__
    await self.error_middleware(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 178, in __call__
    raise exc from None
File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 156, in __call__
    await self.app(scope, receive, _send)
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 73, in __call__
    raise exc from None
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 62, in __call__
    await self.app(scope, receive, sender)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 590, in __call__
    await route(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 208, in __call__
    await self.app(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
File "./tester.py", line 34, in push_update_request_to_nsq
    nsq_dump = requests.post( "http://%s/pub" % ( NSQ_HTTP_WRITER[ 0 ] ), params= { "topic": "nsq_topic" }, data= json_object )
File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 495, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

Я заметил, что такая же проблема возникает, когда я пытаюсь сделать это в Tornado. Созданиеrequests попадание изнутри сервера торнадо вызывает ту же ошибку.

0 ответов

Другие вопросы по тегам