Making put/post from Tornado doesent work - http

I am trying to make a PUT method (or POST) to DropBox api, but it doesent work, I get a GET instead?
import tornado.ioloop
import tornado.web
from tornado.httputil import HTTPHeaders
from tornado.httpclient import HTTPClient, HTTPRequest
url = "https://api-content.dropbox.com/1/files_put/sandbox/world.txt"
class MainHandler(tornado.web.RequestHandler):
def post(self):
headers = HTTPHeaders({'Authorization': 'Bearer TOKEN_FOR_DROPBOX'})
HTTPClient().fetch(
HTTPRequest(url, 'PUT', body="hello there", headers=headers))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
Update: using GET makes an error: HTTPError: HTTP 400: Bad Request
Here is a new code:
import tornado.ioloop
import tornado.web
from tornado.httpclient import HTTPClient, HTTPRequest
url = "https://api-content.dropbox.com/1/files_put/sandbox/wor.txt"
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.set_header('Authorization', 'Bearer DROPBOX_TOKEN')
self.set_header('Content-Type', 'text/plain')
HTTPClient().fetch(
HTTPRequest(url, 'PUT', body="hello there"))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
but get this error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado\web.py", line 1415, in _execute
result = yield result
File "C:\Python27\lib\site-packages\tornado\gen.py", line 870, in run
value = future.result()
File "C:\Python27\lib\site-packages\tornado\concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "C:\Python27\lib\site-packages\tornado\gen.py", line 230, in wrapper
yielded = next(result)
File "C:\Users\Abdelouahab\Desktop\ttttt.py", line 14, in get
HTTPRequest(url, 'PUT', body="hello there"))
File "C:\Python27\lib\site-packages\tornado\httpclient.py", line 102, in fetch
self._async_client.fetch, request, **kwargs))
File "C:\Python27\lib\site-packages\tornado\ioloop.py", line 445, in run_sync
return future_cell[0].result()
File "C:\Python27\lib\site-packages\tornado\concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
HTTPError: HTTP 401: Unauthorized
ERROR:tornado.access:500 GET / (::1) 806.00ms
I tried using an HTTP request builder extension from Mozilla, and it worked, so I guess the problem is how to do it on Tornado?

Sorry, it seems that it missed the content-type
import tornado.ioloop
import tornado.web
from tornado.httputil import HTTPHeaders
from tornado.httpclient import HTTPClient, HTTPRequest
from tornado.gen import coroutine
url = "https://api-content.dropbox.com/1/files_put/sandbox/wor.txt"
class MainHandler(tornado.web.RequestHandler):
#coroutine
def get(self):
headers = HTTPHeaders({'Authorization': 'Bearer DROPBOX_TOKEN', 'Content-Type':'text/plain'})
HTTPClient().fetch(
HTTPRequest(url, 'PUT', body="hello there", headers=headers))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()

Related

TypeError: register_tortoise() got an unexpected keyword argument 'add_exeption_handlers'

Code was copies from https://testdriven.io/courses/tdd-fastapi/postgres-setup/ but it show an exeption while running with uvicorn
import os
from fastapi import FastAPI, Depends
from tortoise.contrib.fastapi import register_tortoise
from app.config import get_settings, Settings
app = FastAPI()
register_tortoise(
app,
db_url=os.environ.get("DATABASE_URL"),
modules={"models": ["app.models.tortoise"]},
generate_schemas=True,
add_exeption_handlers=True,
)
#app.get("/ping")
async def pong(settings: Settings = Depends(get_settings)):
return {
"ping": "pong!",
"environment": settings.environment,
"testing": settings.testing
}

How to get graphiql ide while dependancy Injection in graphql fastapi?

Here is my code so far, I want to inject AuthJWT as dependancy:
from starlette.graphql import GraphQLApp
from starlette.requests import Request as Rq
from fastapi_jwt_auth import AuthJWT
graphql_app = GraphQLApp(schema=graphene.Schema(query=Query, mutation=Mutation))
#router.post("/gql")
async def graph(request: Rq, Authorize: AuthJWT = Depends() ):
request.state.authorize = Authorize
return await graphql_app.handle_graphql(request=request)
app.include_router(router)
Its working fine with post request on insomnia ide but I am unable to see the graphiql ide in the browser in "localhost:8000/gql" url
It gives error: "GET /gql HTTP/1.1" 405 Method Not Allowed
How can I get the graphiql ide?
Is it possible to get the ide by Custom Request and APIRoute class? https://fastapi.tiangolo.com/advanced/custom-request-and-route/
Answer by #IndominusByte
import graphene
from fastapi import FastAPI, Request, Depends
from fastapi_jwt_auth import AuthJWT
from starlette.graphql import GraphQLApp
from starlette.datastructures import URL
from pydantic import BaseModel
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
#AuthJWT.load_config
def get_config():
return Settings()
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
authorize = info.context['request'].state.authorize
access_token = authorize.create_access_token(subject=name)
return "Hello " + name + "access_token" + access_token
app = FastAPI()
graphql_app = GraphQLApp(schema=graphene.Schema(query=Query))
# graphiql ide path here
#app.get('/')
async def graphiql(request: Request):
request._url = URL('/gql')
return await graphql_app.handle_graphiql(request=request)
# use the path for frontend request
#app.post('/gql')
async def graphql(request: Request, authorize: AuthJWT = Depends()):
request.state.authorize = authorize
return await graphql_app.handle_graphql(request=request)
https://github.com/IndominusByte/fastapi-jwt-auth/issues/28

TypeError: 'coroutine' object is not subscriptable in python Quart Framework

from quart import Quart, request, render_template, jsonify
import json
import os, sys
import pandas as pd
import requests
import asyncio
from pylon.model.db_models import RawFiles
from pylon.orm import db
app = Quart(__name__)
#app.route('/upload', methods=['POST'])
async def handle_form():
f = await request.files['filename']
f.save(f.filename)
data = pd.read_csv(f.filename)
data.to_json("json_data.json")
data = pd.read_json("json_data.json")
os.remove("json_data.json")
os.remove(f.filename)
print(type(data))
print(data)
return ""
#app.route("/")
async def index():
return await render_template('upload.html')
if __name__ == "__main__":
app.run(host="bheem11.arch.des.co", port=5043, debug = True)
I am getting one error described in title. I am working in quartz framework in python. Hoping for proper solution. Actually i am getting coroutine error when #app.route("/upload", methods = "post") execute.
This line await request.files['filename'] should be (await request.files)['filename']. Without the parenthesis everything to the right of await is evaluated first, which results in the attempt to subscribe (['filename'] operation) the files attribute. This doesn't work as the files attribute returns a coroutine - which is not subscriptable. There is more on this in the Quart documentation.

Tornado performance issue with MySQLand Redis

I have a tornado server running with MySQL for DB and Redis for cache. I am using web socket to send/receive data. My code is like this:
Server
import logging
import os.path
import uuid
import sys
import json
import tornadis
import tormysql
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from tornado import gen
from tornado.concurrent import Future
from tornado.options import define, options
#gen.coroutine
def getFromDB(query):
with (yield dbPool.Connection()) as conn:
with conn.cursor() as cursor:
yield cursor.execute(query)
datas = cursor.fetchall()
return datas
return None
#gen.coroutine
def getFromCache(cmd):
pipeline = tornadis.Pipeline()
pipeline.stack_call(cmd)
with (yield cachePool.connected_client()) as singleClient:
redisResult = yield singleClient.call(pipeline)
if isinstance(redisResult, tornadis.TornadisException):
print("Redis exception: %s"%(redisResult))
else:
return redisResult
async def getData(dbQuery, cacheQuery):
waitDict = {}
if dbQuery:
waitDict['db'] = getFromDB(dbQuery)
if cacheQuery:
waitDict['cache'] = getFromCache(cacheQuery)
resultList = []
if len(waitDict) > 0:
await gen.multi(waitDict)
if 'db' in waitDict:
dbRes = waitDict['db'].result()
if dbRes:
for eachResult in dbRes:
changeRes = someFunct(eachResult)
resultList.append(changeRes)
if 'cache' in waitDict:
cacheRes = waitDict['cache'].result()
if cacheRes:
for eachResult in cacheRes:
changeRes = someFunct(eachResult)
resultList.append(changeRes)
return resultList
class SocketHandler(tornado.websocket.WebSocketHandler):
SUPPORTED_METHODS = ("GET")
def open(self):
print("Socket open:%s"%(self))
def on_close(self):
print("Socket closed:%s"%(self))
async def on_message(self, inp):
if requestForData:
ret = await getData(dbQuery, cacheQuery)
self.write_message(ret)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/sock", SocketHandler),
]
define("port", default=8000, help="run on the given port", type=int)
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
print("PORT:%s"%(options.port))
tornado.ioloop.IOLoop.current().start()
I am using tornadis for Redis and tormysql for MySQL.
I am running this setup on amazon linux instance m5.large with 2vCPUs memeory:8Gib.
Client
I am trying to simulate the traffic using web socket. The code is like this:
import sys
import json
import asyncio
import websockets
def getData():
for i in range(100):
async with websockets.connect(SOCKET_URL, extra_headers=extraHeaders) as websocket:
for i an range(100):
await websocket.send("get data")
reply = await websocket.recv()
print(reply)
asyncio.get_event_loop().run_until_complete(getData())
I am running multiple instance of the client.
The server is running good but its able to handle only 25 connections. After 25 connections the delay for the reply from the server increases. I want server to reply to be very fast. How do I decrease the delay for the response? So is there any problem in the code?

HTTP Error 400: Bad Request; google app engine + telegram api

So i'm working on a telegram bot for a multi-player board game. Web hook is set. And there appears to be a http 400 error when the bot tries to privately message each user in the group chat. What happened to the bot is that it got stuck and keeps messaging one player.
my code:
BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'
class WebhookHandler(webapp2.RequestHandler):
def post(self):
urlfetch.set_default_fetch_deadline(60)
body = json.loads(self.request.body)
logging.info('request body:')
logging.info(body)
self.response.write(json.dumps(body))
update_id = body['update_id']
try:
message = body['message']
except:
message = body['edited_message']
message_id = message.get('message_id')
date = message.get('date')
text = message.get('text')
fr = message.get('from')
chat = message['chat']
chat_id = chat['id']
chat_type = chat['type']
fr_user_id = fr['id']
fr_user_name = fr['first_name']
if not text:
logging.info('no text')
return
def reply_to_user(desti_user_id, msg):
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(desti_user_id),
**#line 115!** 'text': msg.encode('utf-8')
})).read()
else:
logging.error('no msg or img specified')
resp = None
logging.info('send response:')
logging.info (resp)
The LOG(google app engine):
HTTP Error 400: Bad Request (/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py:1552)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~orbitaltest2/1.394273849972192493/main.py", line 241, in post
reply_to_user(player.user_id, "you are: a member of the resistance")
File "/base/data/home/apps/s~orbitaltest2/1.394273849972192493/main.py", line 115, in reply_to_user
'text': msg.encode('utf-8'),
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request
not sure what happened.

Resources