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()
Related
I have a virtual machine running on a google cloud project with Debian as is OS. it doesn't have its http or https ports open, but when I run the following code, I get a response.
import urllib
import requests
req = urllib.request.Request("https://google.com")
with urllib.request.urlopen(req) as resp:
message = resp.read()
print(message[:15])
I get a response, b'<!doctype html>'.
I have a flask web app that takes a long time to process a request (around 45 minutes).
from flask import Flask, requests
import os
app = Flask(__name__)
#app.route('/', methods=['POST'])
def index():
payload = json.loads(request.get_data(as_text=True))
# runs long running task
if something_went_wrong:
return "something went wrong", 500
return "the task ended successfully", 200
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
The issue that I am having is that when I run the following code, it hangs on urlopen and eventually times out. I've checked the logs on my flask app. it runs successfully and there's a post 200 in the logs.
import urllib
import request
import json
import google.auth.transport.requests
import google.oauth2.id_token
payload = json.dumps({"key1":"value1", "key2":"value2"}).encode()
req = urllib.request.Request("https://my-service-url.app")
auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, "https://my-service-url.app")
req.add_header("Authorization", f"Bearer {id_token}")
with urllib.request.urlopen(url=req, data=payload, timeout=60*60) as resp:
print(resp.read())
Is the timeout too long and it stops listening somewhere else in the system?
is my flask app not responding properly?
is the time I am asking simply unreasonable?
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')
Here is my simple endpoint:
#app.route('/test', methods=['POST'])
def test():
print(request.data)
return Response("", mimetype='application/json')
The request body is:
"ัะตัั"
And the server prints b'"\xd1\x82\xd0\xb5\xd1\x81\xd1\x82"' for request data.
How to set appropriate charset, providing content type header did nothing?
Also is there a way to get rid of that annoying b at the start of every request body?
For anyone having similar problem:
from flask import Flask
from flask import Response
from flask import reques
import chardet
#app.route('/test', methods=['POST'])
def test():
charset = chardet.detect(request.data)['encoding']
print(request.data.decode(charset))
return Response("", mimetype='application/json')
I was unable to make flask to this for me...
so you have to manually decode the bytes.
I have a simple flask server
import pdb
from flask import Flask, jsonify, abort, make_response, request, send_from_directory
from flask_cors import CORS, cross_origin
from pprint import pprint
import argparse
from mylib.mylib_rest_api import ProcessRestApiRequest
DEBUG=True
app = Flask(__name__)
CORS(app)
parser = argparse.ArgumentParser(description='Run the server')
parser.add_argument('--ip-address', default='127.0.0.1', help='Server IP Address. Default: %(default)s')
parser.add_argument('--port', type=int, default=8081, help='Server port')
args = parser.parse_args()
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
def do_pre_serve_actions():
if not request.json: abort(400)
# Extract the data
dictReq = request.get_json(force=True)
if DEBUG:
pprint('dictReq: '+str(dictReq))
return dictReq
def do_post_serve_actions(dictResp):
if DEBUG:
pprint("dictResp: "+str(dictResp))
dictJSONResp = jsonify(dictResp)
objRespADF = make_response(dictJSONResp)
return objRespADF
#app.route('/<target>', methods=['POST'])
def serve(target):
dictReq = do_pre_serve_actions()
dictResp = ProcessRestApiRequest(dictReq, target)
return do_post_serve_actions(dictResp)
if __name__ == '__main__':
app.run(debug=DEBUG, host=args.ip_address, port=args.port)
This is how a request looks like:
makeRequestAndSendData(xhr, dict) {
dict['Interface'] = this.getChipInterface();
var data = JSON.stringify(dict);
var url = this.server.getUrl();
console.log("url: "+url);
console.log("Request Dictionary:");
console.log(dict);
xhr.open("POST", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Headers","*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Content-type","application/json");
xhr.send(data);
}
Here is what I'm getting:
Failed to load http://192.168.0.132:8084/mychip: Response to preflight
request doesn't pass access control check: The
'Access-Control-Allow-Origin' header has a value 'null' that is not
equal to the supplied origin. Origin 'null' is therefore not allowed
access.
What am I doing wrong? I've looked everywhere online and it seems like it got everything I need. Am I missing something?
This can happen with Chrome and WebKit/Chrome based browsers (Opera, Brave, etc.) if you serve the page from the file system instead of the network. In that case there is no origin site (because it was served from file), and Chrome will send the header Origin: null in the preflight OPTIONS request. Your CORS enabled Flask server will reply with this origin in its preflight response, however, Chrome rejects it as an invalid origin, even though that is what Chrome sent in the first place.
Firefox also sends header Origin: null in the OPTIONS request, but it is OK with the response and so it does issue the actual POST request. I have also found that Chrome on Android does seem to work when loading from the file system.
As a work-around, serve your test file from a HTTP server. The easiest way (for testing purposes only) is to use Python's SimpleHTTPSever. Simply change to the directory containing your test HTML file and run this command:
$ python -m SimpleHTTPServer
It will start a HTTP server listening on port 8000 so you can load the file into your browser using URL http://localhost:8000/cors_test.html for example.
Also note that the Access-Control-Allow-* headers are meant to be sent in the preflight response, not the request. flask-cors will generally handle that for you and the client side XMLHttpRequest object should properly construct the request for you.
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.