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.
Related
I am facing a very weird Issue, In my Flask App when index route (https://sitename.com/) is called everything is fine, but as i navigate to a route like https://sitename.com/about it shows 404 Error, even when About route is created in main.py . This App works all perfect in localhost:5000 but when I deployed it too a VPS It is showing that Error of showing 404 on every route
My main.py
from os import environ
from flask import Flask, redirect, render_template, request, url_for
import requests
import json
import datetime
def getUserData(route):
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
with open("users.txt", "a") as f:
f.write(f"Page Visited: {route}\n")
f.write(f"User Agent: {request.headers.get('User-Agent')}\n")
f.write(f"Remote Addr: {ip}\n")
f.write(f"DateTime: {datetime.datetime.now()}\n")
f.write(f"\n\n\n")
app = Flask(__name__)
app.debug = True
# Website
#app.route('/')
def index():
getUserData("Index Page")
return render_template('index.html')
#app.route('/gallery')
def gallery():
getUserData("Gallery")
return render_template('pages/gallery.html')
#app.route('/faqs')
def faqs():
getUserData("FAQs")
return render_template('pages/faqs.html')
#app.route('/about')
def about():
getUserData("About")
return render_template('pages/about.html')
#app.route('/contact')
def contact():
getUserData("Contact")
return render_template('pages/contact.html')
# 404 Handling
#app.errorhandler(404)
def not_found(e):
getUserData("404 Page")
return render_template("pages/404.html")
if __name__ == '__main__':
app.run()
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)```
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"
The get method on user works if the # api.add_resource(User, '/user/')
line is uncommented, and the other api.add_resource is.
The inverse of that is true to make the post method work.
How can I get both of these paths to work?
from flask import Flask, request
from flask.ext.restful import reqparse, abort, Api, Resource
import os
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
api = Api(app)
class User(Resource):
def get(self, userid):
print type(userid)
if(userid == '1'):
return {'id':1, 'name':'foo'}
else:
abort(404, message="user not found")
def post(self):
# should just return the json that was posted to it
return request.get_json(force=True)
api.add_resource(User, '/user/')
# api.add_resource(User, '/user/<string:userid>')
if __name__ == "__main__":
app.run(debug=True)
Flask-Restful supports registering multiple URLs for a single resource. Simply provide both URLs when you register the User resource:
api.add_resource(User, '/user/', '/user/<userid>')
I have a website that needs to be rebranded depending on the URL that a visitor comes in on. For the most part, the content is the same but the CSS is different. I'm brand new to flask and relatively new to session cookies, but I think the best way to do this is to create a session cookie containing a "client" session variable. Then, depending on the client (brand), I can append a specific css wrapper to a template.
How can I access URL params and set one of the param values to a session variable? For example, if a visitor comes in on www.example.com/index?client=brand1, then I'd like to set session['client'] = brand1.
My app.py file:
import os
import json
from flask import Flask, session, request, render_template
app = Flask(__name__)
# Generate a secret random key for the session
app.secret_key = os.urandom(24)
#app.route('/')
def index():
session['client'] =
return render_template('index.html')
#app.route('/edc')
def edc():
return render_template('pages/edc.html')
#app.route('/success')
def success():
return render_template('success.html')
#app.route('/contact')
def contact():
return render_template('pages/contact.html')
#app.route('/privacy')
def privacy():
return render_template('pages/privacy.html')
#app.route('/license')
def license():
return render_template('pages/license.html')
#app.route('/install')
def install():
return render_template('pages/install.html')
#app.route('/uninstall')
def uninstall():
return render_template('pages/uninstall.html')
if __name__ == '__main__':
app.run(debug=True)
You could do so in a #flask.before_request decorated function:
#app.before_request
def set_client_session():
if 'client' in request.args:
session['client'] = request.args['client']
set_client_session will be called on each incoming request.