I have a simple web server built with Flask. The server listens for JSON post webhooks.
#app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
I need a way to save the incoming JSON data. I am not sure how to go about this. The data doesn't need to be put into tables or configured in anyway.
Use Python's logging facility. An example code below, used from Logging to a file and your snippet shared above.
import logging
from flask import Flask, request
logging.basicConfig(filename='requests.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
request_data = request.get_json()
logging.info(request_data)
if __name__ == '__main__':
logging.info("Running application with local development server!")
app.run()
The above code will log your requests with timestamps to a file and append to the file every time a new request is made.
from flask import request, jsonify
def webhook():
resp=''
if request.method == 'POST':
my_form_field = request.form['my_form_field']
if my_form_field:
resp = 'Form data received'`enter code here`
return jsonify(resp = resp) #you may collect this response with JQuery
else:
resp = 'Form field is empty'
return jsonify(resp = resp)```
Related
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 10 months ago.
I want to send some POST data to a flask webpage then have it display that data but when I try to send the data {"hi": "hi"} it gives me these errors:
code 400, message Bad request syntax ('hi=hi')
"None / HTTP/0.9" HTTPStatus.BAD_REQUEST -
my code is this:
from flask import Flask, request
app = Flask("__name__")
#app.route("/", methods=['GET', 'POST'])
def hi():
return "hi"
if request.method == "POST":
data = request.values
return f"<p>{data}</p>"
the flask app:
and the post data sending program:
import requests
requests.post('http://127.0.0.1:5000', data={ "req": "hi" })
am I just not understanding POST requests right or am I doing something really wrong?
please see this answer regarding how to access the request's data.
the requests.post you are using as http client is sending the data as form-encoded, so we could use Flasks' request.form to access the data. Also your function needs some restructuring, else it will always return "hi", we can make it:
from flask import Flask, request
app = Flask("__name__")
#app.route("/", methods=['GET', 'POST'])
def hi():
if request.method == "GET":
return "hi"
if request.method == "POST":
# data = request.values
# data will be = req if your POST request has req field, else will be = field: req was not provided
data = request.form.get("req", "field: req was not provided")
return f"<p>{data}</p>"
if you dont know the fields the POST request will contain, you can use this loop to get the fields and their values:
#app.route("/", methods=['GET', 'POST'])
def hi():
if request.method == "GET":
return "hi"
if request.method == "POST":
# data = request.values
for field in request.form:
print(field, request.form.get(field))
return "hi"
I'm currently having some trouble with my flask webapp, where I have written it as below, but when I try to run the flask app, I run into a Bad Request Error. (The browser (or proxy) sent a request that this server could not understand)
Essentially, I am trying to allow users to log in to an external website through the flask webapp
What is the cause of this error? Apologies if I am making a stupid mistake, I'm very new to flask.
from flask import Flask,render_template, request, redirect
import requests
from bs4 import BeautifulSoup as bs
app = Flask(__name__)
#app.route('/', methods = ["POST", "GET"])
def login():
username = request.form['username']
pin = request.form['password']
s = requests.Session()
r = s.get("https://www.example.com/User/Login")
soup = bs(r.text, 'html.parser')
loginToken = soup.findAll(attrs={"name" : "__RequestVerificationToken"})[0]['value']
#Create Login Payload
login_payload = {
"__RequestVerificationToken" : loginToken,
"UserName" : username,
"Password" : pin,
"returnUrl" : "https://example.com/user-action/?action=login&returnUrl=https://www.example.com/User/Information",
}
#Post Login Payload
r = s.post("https://www.example.com/Account/Login", data = login_payload)
if r.status_code == 200:
return render_template('home.html')
else:
return render_template('login.html')
return render_template('login.html')
#app.route('/home') #If login works, redirect to this page
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run(debug = True)
In addition, if there are other resources that I could refer to with regards to allowing a user to log in to a external URL from the flask webapp as compared to the conventional tutorials that only show a user logging in to the flask webapp itself, do share it with me, thank you!
Your endpoint' s has two Http verbs ["POST", "GET"]. You should specify your methods as below.
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
#something do stuff
return render_template("your_html_page")
if request.method == "POST":
#something do stuff
return your_response, 200
Edited Block
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
return render_template('login.html')
if request.method == "POST":
#same logic here
if status_code == 200:
return redirect(url_for('home'))
return render_template('login.html')
New to Flask and Python. I've cloned a github Flask chat app example and am trying to get a referrer URL (i.e. the URL the user was in before going into my app). However, when I run the app locally, the referrer link always come back as None if the request comes from an external URL. If it is sent from within the app, I am getting the right referrer URL.
Here's the relevant bits of code. I've tried looking at previous questions, but couldn't find a solution.
My routing logic:
from flask import session, redirect, url_for, render_template, request
from . import main
from .forms import LoginForm
#main.before_request
def before_request():
print("Ref1:", request.referrer)
print("Ref2:", request.values.get("url"))
#main.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
ip_address = request.access_route[0] or request.remote_addr
print("ip_addr:", ip_address)
if form.validate_on_submit():
session['name'] = form.name.data
session['room'] = form.room.data
return redirect(url_for('.chat'))
elif request.method == 'GET':
form.name.data = session.get('name', '')
form.room.data = session.get('room', '')
return render_template('index.html', form=form)
#main.route('/chat')
def chat():
name = session.get('name', '')
room = session.get('room', '')
if name == '' or room == '':
return redirect(url_for('.index'))
return render_template('chat.html', name=name, room=room)
My main app code is:
#!/bin/env python
from app import create_app, socketio
app = create_app(debug=True)
if __name__ == '__main__':
socketio.run(app)
Would really appreciate any advice.
Thanks!
i'm new to Flask. And i'm trying to redirect the user to a "success" page where he can download the csv file that my program had create for him.
so my server.py look like this:
from flask import Flask, request, abort, redirect
from flask_cors import cross_origin
import process
app = Flask(__name__)
#app.route('/ind', methods=['POST'])
#cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def ind():
if not request.json:
abort(400)
my_json = request.json
reponse = process.process(my_json)
if reponse:
return redirect("http://localhost:8080/success", code=302)
else:
return redirect("http://localhost:8080/fail", code=302)
#app.route('/position', methods=['POST'])
#cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def position():
if not request.json:
abort(400)
my_json = request.json
reponse = process.process(my_json)
if reponse:
return redirect("http://localhost:8080/success", code=302)
else:
return redirect("http://localhost:8080/fail", code=302)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5050, debug=True)
my process.py where the JSON that i received is transformed and transcripts to a csv file, look like this:
def process(my_json):
[blablabla...]
return True
"reponse" is always True but no redirection, what am i doing wrong ?
Assuming you have handlers for routes /success and /fail, you can use url_for.
from flask import url_for
#app.route('/position', methods=['POST'])
def posistion():
# ...
if response:
return redirect(url_for('/success'), code=302)
return redirect(url_for('/fail'), code=302)
Do not hard-code urls to other routes of your flask application. This can lead to your case, when your server is running on port 5050 and your urls are targeting port 8080.
How do I request data (in form of image) to server in Flask?
import os
from flask import Flask, request, redirect,url_for, Response
from flask import Markup, send_from_directory
from werkzeug.utils import secure_filename
UPLOAD_IMAGE = '/home/tarak/Pictures/Wallpapers/m31.jpg'
ALLOWED_EXTENSIONS = set(['jpg','png','txt','jpeg','gif'])
app = Flask(__name__)
#app.route('/image', methods=['POST'])
def image():
if request.method == 'POST':
f = request.files['UPLOAD_IMAGE']
request_
print("Image Received!!")
return "This is the homepage."
if __name__ == "__main__":
app.run(debug=True)
I am getting 404 Not Found Error on localhost:5000/image.
You get the error because, your route #app.route("/image", methods=['POST']) accepts only a post request, and when opening the URL in your browser it recieves a 'GET' request.
If you modify it to #app.route("/image", methods=['GET', 'POST']) or remove methods=.. you will see in your browser "This is the homepage"