How can I add webhook events to a flask server? - python

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"}}

Related

how to fetch data from flask app in react app on local server

I have a flask app running on localhost:5000:
from flask import Flask
app = Flask(__name__)
#app.route("/api")
def parse():
return {"test": "json"}
if __name__ == "__main__":
# for production change debug to False
app.run(debug=True)
And on the front end I'm fetching the data here:
useEffect(() => {
fetch("http://localhost:5000/api")
.then((res) => res.json())
.then((data: Data) => {
setData(data);
console.log(data);
});
}, []);
When I try and fetch the data from my react-app I get this error in the console:
I've seen a bunch of answers to similar questions, but all the other questions were more complicated than mine and I don't know what to add to my flask app since mine is pretty bare bones.
Luckly it's pretty simple to solve it. All you need to do is to install flask-CORS with pip install flask-cors and then add an CORS header on your app, like this:
from flask_cors import CORS
from flask import Flask
app = Flask(__name__)
CORS(app)
#app.route("/api")
def parse():
return {"test": "json"}
if __name__ == "__main__":
# for production change debug to False
app.run(debug=True)
For more information, visit flask-cors documentation
#app.route("/", methods=["GET"])
def get_example():
"""GET in server"""
response = jsonify(message="Simple server is running")
# Enable Access-Control-Allow-Origin
response.headers.add("Access-Control-Allow-Origin", "*")
return response
or

Cant run flask on ngrok

from flask import Flask, escape, request
app = Flask(__name__)
run_with_ngrok()
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
When I run the this from terminal with "flask run" it doesn't print an ngrok link.
Im i an virtual env and i have tried running it with python "file name" and it did not work.
if you are trying to expose your ip through ngrok, you can try tunneling with ngrok on terminal for the flask app's port
your app code should look like :
from flask import Flask, escape, request
app = Flask(__name__)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(port=5000)
you can tunnel the flask app port with the following command:
ngrok http 5000
here the port 5000 denotes the flask app port.
I think you forgot to add this part to end of your file
if __name__ == "__main__":
app.run()
from flask_ngrok import run_with_ngrok
from flask import Flask, escape, request
app = Flask(__name__)
app.secret_key = '33d5f499c564155e5d2795f5b6f8c5f6'
run_with_ngrok(app)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(debug=True)
We can grab token from ngrok.com website by signin
In terminal we need to run like
ngrok config add-authtoken <your_token>
ngrok http 5000
for flask it is 5000 and for other application it would be different
And we also need to run our application side by side

How to redirect in aws app runner with flask

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)

Trouble with accessing flask-socketio session

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.

Run a little HTTP server to check callback

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/

Categories

Resources