I would like to run a script that will create a simple HTTP server and run a function for each request.
I am using Python to test an API that should give me a callback.
For now, I am using http://requestb.in/ to test the callback, but I would like to test it directly in my python script.
Is it possible to run a callback server bind on localhost:6548 and test something base on a request?
Thank you for your help.
You could use wsgiref to host a simple WSGI web application. Example:
from wsgiref.simple_server import make_server
import datetime
def application(environ, start_response):
start_response('200 OK', [('Content-type', 'text/plain')])
retval = [
str(environ),
"\n",
"Hello world!\n",
str(datetime.datetime.now())
]
return retval
make_server('localhost', 6548, application).serve_forever()
This code creates a Python WSGI web application and serves that app on http://localhost:6548.
You could use the Flask micro framework. Here is a quick example:
from flask import Flask, request
app = Flask(__name__)
#app.route('/firs_call', methods=['POST'])
def first_callback():
if request.method == 'POST':
result = request.data
client_ip = request.remote_addr
return "OK"
#app.route('/second_call', methods=['GET'])
def second_callback():
if request.method == 'GET':
#....
pass
return "OK"
if __name__ == '__main__':
app.debug = True
app.run("127.0.0.1")
You can reach this web application at http://127.0.0.1:5000/
Related
I am trying to deploy my flask application to aws app runner, locally everything works perfectly. But I can't figure out how to redirect to another page of my website in app runner
My code looks similar to this
from flask import Flask, url_for
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect(url_for("redirect_to"))
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
App runner provided "Default domain" that redirects all traffic to my app, that is running on 0.0.0.0:8000. When I request default-domain.awsapprunner.com/hello, it successfully redirects to 0.0.0.0:8000/hello, but when I try to request default-domain.awsapprunner.com/redirect_from page loads forever. I think it happens because my app redirects to 0.0.0.0, and app runner expects that all traffic comes to default-domain.awsapprunner.com but I am not sure
What is the best way to fix this problem?
from flask import Flask, url_for, redirect
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect("http://YOUR_APP_URL.com/redirect_to")
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
I have been searching everywhere for tutorials on how to create and implement webhooks which listen for events within a back-end API. For instance, if I had a server written in python flask, how would I listen to server-side events (example: user has created 100 total records) which then executes some more back-end code or requests external data?
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return {"status": 200}
#Some webhook code listening for events in the server
if __name__ == '__main__':
app.run()
What do I write to listen for server events?
You can use flask feature called before_request it like this
from flask import Flask, jsonify, current_app, request
app = Flask(__name__)
#app.before_request
def hook_request():
Flask.custom_variable = {
"message": "hello world",
"header": request.args.get("param", None)
}
#app.route('/')
def home():
variable = current_app.custom_variable
return jsonify({
"variable": variable,
})
if __name__ == '__main__':
app.run()
and to test it
like this
→ curl http://localhost:5000/
{"message":"hello world"}
→ curl http://localhost:5000\?param\=example
{"variable":{"header":"example","message":"hello world"}}
When I run my local application with flask-socketio I can access session using from flask import session, but when I run it with gunicorn on server (gunicorn --worker-class eventlet -w 1 app:app) it return me session.keys() as Array[0].
How could I fix it to establish this local-proxy with session on server?
Thanks
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#app.before_request
def before_request():
session['key_1'] = 'Hello,'
session['key_2'] = 'World'
#app.route('/')
def index():
return render_template('index.html')
#socketio.on('connect', namespace='/')
def socket_connect():
session_keys = session.keys()
emit('connect response', {
'session_keys': session_keys
})
#socketio.on('disconnect', namespace='/')
def socket_disconnect():
print('Client disconnected', request.sid)
if __name__ == '__main__':
socketio.run(app)
I found a solution.
Session was dissapearing and could not be shared to socketio, because I added redirect page rules on cloudflare for my domain.
When I changed Forwarding type of all rules to 302 - Temporary everything worked well.
I have pip-installed Flask and HTML5 on my Window-system. When I start the Hello World!-program with IDLE, I get a red message in the Python-Shell:
"* Running on xxxx://127.0.0.1:5000/". (xxxx = http)
And when I start it with app.run(debug=True) another red message appears:
"* Restarting with reloader".
My browser (Firefox) shows no reaction.
What can I do to get 'Hello World' in a new tab of Firefox?
The Code is:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
return and app.run are indended
You have to open a new tab with this url:
http://127.0.0.1:5000/
You need to actually open the page in your browser - it won't open itself. Open Firefox and navigate to
127.0.0.1:5000
(it's a URL)
When you run your code, it sits around waiting for a request from the user. When it gets a request, it'll return a response, and that's (sort of) what you see in your browser. Going to a URL is how you send that request - Flask will interpret anything sent to 127.0.0.1:5000 as a request, and try to match the URL to one of your #app.route decorators. For example, if you were to have a function decorated with #app.route("/hello"), then when you go to 127.0.0.1:5000/hello, Flask would run that function to determine the response.
Try out this code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
refrence Flask at first run: Do not use the development server in a production environment
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Try this, this works for me. Open your firefox browser and go to the address given in the output. ex: http://XXXX.X.X.X:5000/
I kick off my flask app like this:
#!flask/bin/python
from app import app_instance
from gevent.pywsgi import WSGIServer
#returns and instance of the application - using function to wrap configuration
app = app_instance()
http_server = WSGIServer(('',5000), app)
http_server.serve_forever()
And then when I try to execute this code, the requests call blocks until the original request times out. I'm basically invoking a webservice in the same flask app. What am I misunderstanding about gevent? Wouldn't the thread yield when an i/o event occurred?
#webapp.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm(request.form, csrf_enabled=False)
data = None
if request.method == 'POST' and form.validate():
data= {'email': form.email, 'auth_token': form.password,
'name' : form.name, 'auth_provider' : 'APP'}
r = requests.post('http://localhost:5000', params=data)
print('status' + str(r.status_code))
print(r.json())
return render_template('register.html', form=form)
I believe the issue is likely that you forgot to monkey patch. This makes it so that all of the normally blocking calls become non-blocking calls that utilize greenlets. To do this just put this code before you call anything else.
from gevent import monkey; monkey.patch_all()
Go to http://www.gevent.org/intro.html#monkey-patching for more on this.