Jsonified Response from server [duplicate] - python

This question already has answers here:
Flask hangs when sending a post request to itself
(2 answers)
Closed 5 years ago.
I was trying to make a get request and obtain a jsonified response. But when i try this the request never gets completed. The browsers keeps on loading status only
#app.route('/user/json')
def json():
users = User.query.all()
list_serialized = [user.serialize() for user in users]
return jsonify(list_serialized)
#app.route('/recieve')
def recieve():
headers = {'content-type': 'application/json'}
users = requests.get('http://127.0.0.1:5000/user/json', headers=headers).json()
print users
return users

use app.run(threaded=True) for running app in main function.

Related

Python GET Request with set-cookies [duplicate]

This question already has answers here:
How can I use cookies in Python Requests?
(4 answers)
Closed 3 years ago.
I am trying to get some data from a webpage using python requests which needs to be logged in first.The login http request "response header" contains "set-cookie" parameters which is used for the next http request of the webpage. Could any tell me how to use the set-cookie for the consecutive GET request of the webpage
Try this
session = requests.Session()
response = session.get('http://google.com')
print(session.cookies.get_dict())
Or without using sessions use
response = requests.get('http://google.com')
response.cookies

Mailgun forwarding e-mail as POST data to Python Flask [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I can't figure this one out, it's not in the request.JSON and the request.data is coming up as empty bytes in the debug. There appears to be a post but the data is disappearing? Is this a bug with Flask?
Here's a link to their documentation page that has a Django example: https://documentation.mailgun.com/en/latest/quickstart-receiving.html#supported-actions-for-routes
Figured this out: Clue was in the header
'Content-Type': 'application/x-www-form-urlencoded'
Flask automatically strips out form data into request.form leaving request.data and request.json empty:
#app.route("/test-mail/", methods=["POST"], strict_slashes=False)
def test_mail():
print(request.form)
return 'OK'

Flask : Server not responding on internal API access [duplicate]

This question already has answers here:
Flask hangs when sending a post request to itself
(2 answers)
Closed 5 years ago.
I was trying develop web application using flask, below is my code,
from sample import APIAccessor
#API
#app.route('/test/triggerSecCall',methods=['GET'])
def triggerMain():
resp = APIAccessor().trigger2()
return Response(json.dumps(resp), mimetype='application/json')
#app.route('/test/seccall',methods=['GET'])
def triggerSub():
resp = {'data':'called second method'}
return Response(json.dumps(resp), mimetype='application/json')
And my trigger method contains the following code,
def trigger2(self):
url = 'http:/127.0.0.1:5000/test/seccall'
response = requests.get(url)
response.raise_for_status()
responseJson = response.json()
if self.track:
print 'Response:::%s' %str(responseJson)
return responseJson
When I hit http://127.0.0.1:5000/test/seccall, I get the expected output. When I hit /test/triggerSecCall, the server stop responding. The request waits forever.
At this stage, I am not able to access any apis from anyother REST clients. When I force stop the server(Ctrl+C) I am getting response in the second REST client.
Why flask is not able to serve to internal service call?
I guess you are using the single threaded development server and not a WSGI setup for production.
Since the server has only one thread is can handle one request at a time. The first request will be executed, resulting in the requests.get(...) which will open a second request that can not be handled until the first request is complete, a dead lock.
The best solution would be to just call triggerSub() to get the result instead of using an HTTP request.

Why my POST method from a web service refuses my json data? [duplicate]

This question already has answers here:
How to POST JSON data with Python Requests?
(10 answers)
Closed 5 years ago.
I want to build a web service in python using flask library but I got stuck at the beginning. I managed to succeed with Get methods but I am having some trouble with my POST method. The problem I am having is that when I send a Json data with the POST method my program crashes with the following error: "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:"
If I send the request without the data everything works fine.
Below is the code for the method POST from the server. I kept it basic so I could find the error easier.
class End_Point(Resource):
def POST(self):
return 1
api.add_resource(End_Point,'/end_point')
Here is how I make the request that crashes my program:
url = 'http://127.0.0.1:5000/end_point'
response = requests.post(url, data=json.dumps("123"), headers=headers)
Do you have any idea what am I doing wrong?
You need to send it as an object/dictionary so you can actually access the value by a name on the server.
server:
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('mynum', type=int, help='mynum is a number')
class EndPoint(Resource):
def post(self):
args = parser.parse_args()
return {"status": "ok", "mynum": args['mynum']}
api.add_resource(EndPoint, '/end_point')
if __name__ == '__main__':
app.run(debug=True)
client:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://localhost:5000/end_point'
response = requests.post(url, data=json.dumps(dict(mynum=123)), headers=headers)
print('response', response.text)

Enter page that you have to be logged in [duplicate]

This question already has an answer here:
Using Python Requests: Sessions, Cookies, and POST
(1 answer)
Closed 6 years ago.
I need To send get request To page that I have to login first
using requests module
I tried to first send post request and make login with my information
Then using cookies which is [phpsessionid] & send it with the get request
cookie = {'PHPSESSID': 'm7v485i9g1rfm3tqcn0aa531rvjf5d26'}
x = requests.get('https://www.example.com/',cookies=cookie)
but it doesn't work !
And idea on how to open the page ?
Instead of trying to hijack a session, login using requests with something like:
session = requests.session()
session.post(loginUrl, data={'username':username, 'password':password, ... (anything else the login page posts)}
response = session.get(anyInternalPage)

Categories

Resources