I want to make a website with Flask to show some data posted from another website such as this one.In short,I want to list the data from that website.
Should I use this method: flask.Request.get_json()?
I do not know how to get a Request object. Could you show me some demos about that?
I am using Python 3 and Flask.
import requests
def get(url):
try:
res = requests.get(url)
return res.json()
except:
return False
data = get('http://example.com')
print(data)
In short,I want to list the data from that website.
The accepted answer seem not use flask, so I'll add some:
from flask import jsonify, Flask
import requests
app = Flask(__name__)
#app.route('/')
def index():
r = requests.get('https://api.github.com/users/runnable')
return jsonify(r.json())
Should I use this method: flask.Request.get_json()
No, it is for parsing the incoming json request data. No one is sending requests to you.
Related
This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 3 years ago.
So the authorization request url is correct and it successfully redirects to redirect_url which is /loginAuthorized. I can plainly see that a code is added as in
http://127.0.0.1:5000/loginAuthorized/?code=SOME_CODE`
but can't grab it on the code. When I print path, it just prints loginAuthorized/ wihtout code. I can ask users to manually copy paste code from url, but it will not be convenient so want to avoid asking that.
import re
import requests
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def main():
# encoded url with information needed to request an authorization
url = "https://kauth.kakao.com/oauth/authorize?client_id=MY_CLIENT_ID&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2F%2FloginAuthorized/&response_type=code"
return render_template('index.html', request_url=url)
# If you authorize the service, it redirected to this url
# Catch any url that has /loginAuthorized as its base
#app.route("/loginAuthorized", defaults={"path": ""})
#app.route("/<path:path>")
def loginAuthorized(path):
print('a')
print(path) # "loginAuthorized/" is printed, there is no code
print('b')
if __name__ == "__main__":
app.run()
You can use request flask module to get query params from URL
Import request using
from flask import request
Then to get code query param from URL use.
request.args.get('code')
I want to forward a GET request that I get from a client to a different site,
In my case- A m3u8 playlist request to a streaming site to handle.
Does anyone know how can it be done?
If you want to proxy, first install requests:
pip install requests
then, get the file in the server and serve the content, ej:
import requests
from flask import Flask, Response
app = Flask(__name__)
#app.route('/somefile.m3u')
def proxy():
url = 'https://www.example.com/somefile.m3u'
r = requests.get(url)
return Response(r.content, mimetype="text/csv")
app.run()
If you just want to redirect, do this (requests not needed):
from flask import Flask, redirect
app = Flask(__name__)
#app.route('/redir')
def redir():
url = 'https://www.example.com/somefile.m3u'
return redirect(url, code=302)
app.run()
I have a simple http client in python that send the http post request like this:
import json
import urllib2
from collections import defaultdict as dd
data = dd(str)
req = urllib2.Request('http://myendpoint/test')
data["Input"] = "Hello World!"
response = urllib2.urlopen(req, json.dumps(data))
On my server side with Flask, I can define a simple function
from flask import request
#app.route('/test', methods = ['POST'])
def test():
output = dd()
data = request.json
And the data on server will be the same dictionary as the data on the client side.
However, now I am moving to Klein, so the server code looks like this:
#app.route('/test', methods = ['POST'])
#inlineCallbacks
def test(request):
output = dd()
data = request.json <=== This doesn't work
and the request that's been used in Klein does not support the same function. I wonder is there a way to get the json in Klein in the same way I got it in Flask? Thank you for reading this question.
Asaik Klein doesn't give you direct access to the json data, however you can use this code to access it:
import json
#app.route('/test', methods = ['POST'])
#inlineCallbacks
def test(request):
output = dd()
data = json.loads(request.content.read()) # <=== This will work
I want to use flask to return JSON to the brower with or without simplejson (with appropriate headers) here is what I have so far for my flask application:
#app.route('/')
def hello_world():
QUERY_URL="http://someappserver:9902/myjsonservlet"
result = simplejson.load(urllib.urlopen(QUERY_URL))
return result;
Assuming the JSON output returned is:
{"myapplication":{"system_memory":21026160640.0,"percent_memory":0.34,
"total_queue_memory":4744,"consumers":1,"messages_unacknowledged":0,
"total_messages":0,"connections":1}
When I visit the page http://localhost:5000 however, I get a Internal Server Error. What must I do with "result" to get it to display appropriately? Or is there some way I can tell it to return with json headers?
When I add a print statement to print the result I can see the JSON, but in the browser it gives me an Internal Server Error.
import requests
r = requests.get(QUERY_URL)
return r.json
#normal return
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
jsonify is available in flask. Here is the docs
I am currently creating a RESTful webservice in python utilizing flask. Now on the client side that will use / implement the webservice APIs, I want to get the output in XML (or JSON) format. Do you have any ideas on how to do this? I already tried jsonify but no success. Also, i prefer an XML format in output, but again, I don't know how to do it. So I hope someone can give me ideas.
Below are dummy code snippets to hopefully clarify my question:
/*** webservice ***/
from flask import Flask, jsonify
app = Flask(__name__)
#app.route("/")
def hello_world():
return jsonify(message = "hello world!")
if __name__ == "__main__":
app.run()
/*** client code ***/
import urllib2
server = "http://localhost:5000/"
req = urllib2.Request(server)
# req has no data at all :(
Hoping to receive feedback. Than=ks in advance
The server code runs fine. You should test it with a normal web browser and you will see the json response. Your client code isn't complet. There my correction:
import urllib2
server = "http://localhost:5000/"
req = urllib2.Request(server)
response = urllib2.urlopen(req)
print response.read()
A better way to do http requests in python is to use the requests module which provides a very simple but very powerful api.
import requests
res = requests.get("http://localhost:5000/")
print res.text
To build xml response I would recommend lxml with his cool etree modul. There is also a etree modul in the standart lib under xml.etree.