how to set_cookie value as an integer for Python Flask? - python

I'm just learning the Flask framework and while doing an exercise I got caught up with an issue, for some reason I cannot store cookie as an integer and when I convert the variable count to a string before storing it works. Here is my code:
from flask import Flask, render_template, session, request, make_response, redirect
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
#app.route('/')
def index():
if 'counter' in request.cookies:
count = int(request.cookies.get('counter')) + 1
resp = make_response(render_template('index.html', c=count))
resp.set_cookie('counter', str(count))
else:
resp = make_response(render_template('index.html', c=1))
resp.set_cookie('counter', '1')
return resp
#app.route('/addtwo', methods=['get'])
def add_two():
if 'counter' in request.cookies:
count = int(request.cookies.get('counter')) + 1
resp = make_response(redirect('/'))
resp.set_cookie('counter', str(count))
else:
resp = make_response(redirect('/'))
resp.set_cookie('counter', '2')
return resp
#app.route('/reset', methods=['get'])
def reset():
resp = make_response(redirect('/'))
resp.set_cookie('counter', '0')
return resp
if __name__ == "__main__":
app.run(debug=True)

Answer is in the comments.
To not leave the question without an answer - quoting dirn:
Checking if 'counter' in request.cookies and using request.cookies.get
is unnecessary. If the if passes, the key is there and can be accessed
directly request.cookies['counter']. Better yet, you can remove the if
entirely and just use int(request.cookies.get('counter', 0)) + 1
regardless of whether or not the cookie has already been set

Related

How to Display The output of nikto tool on a Page using flask

I want to display the result of this Python code on a page instead of console
from flask import Flask, render_template, request
import subprocess
import requests
from bs4 import BeautifulSoup
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/scan', methods=['POST'])
def scan():
url = request.form['url']
if not url.startswith("http"):
url = "http://" + url
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
cmd = f"nikto -h {url}"
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
result = ""
while True:
out = p.stderr.read(1).decode('utf-8')
if out == '' and p.poll() != None:
break
if out != '':
result += out
return render_template('index.html', output=result)
if __name__ == '__main__':
app.run(debug=True)
The result is showing on terminal but i want to make it show on Page

Why database datas are being deleted after restarting flask server?

Recently, I have started flask. I found flask-sqlalchemy to work with flask. So I was using this. But I faced some problems. I am working on repl.it. When the repl goes assleep, I tried to use with the flask enabled website. But saw that no datas were showing. But before that I added a lot of datas. I can't figure out what is wrong but could you help me?
It may help you:
from flask_sqlalchemy import SQLAlchemy
import re
from flask import Flask, abort, jsonify, redirect, request
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class apikey(db.Model):
apikey = db.Column(db.String(25), primary_key=True, unique = True)
def __init__(self, apikey):
self.apikey = apikey
class shorturl(db.Model):
short_query = db.Column(db.String(15), primary_key=True, unique = True)
original = db.Column(db.String(1000))
visits = db.Column(db.Integer)
def __init__(self, short_query,original, visits):
self.short_query = short_query
self.original = original
self.visits = visits
def url_valid(url):
return re.match(regex, url) is not None
def bad_request(message):
response = jsonify({'message': message})
response.status_code = 400
return response
def errreq(message):
response = jsonify({'message': message})
response.status_code = 404
return response
#app.route('/')
def show_all():
return redirect("https://www.cburst.ml", code=301)
#app.route('/addapi', methods=['GET'])
def addapi():
if request.args.get('apikey') is not None:
api_key = request.args.get('apikey')
apiadd = apikey(apikey=api_key)
db.session.add(apiadd)
db.session.commit()
return jsonify({'message':"Done"}), 200
else:
return bad_request("Nothing Provided")
#app.route('/add', methods=['POST'])
def add():
if not request.json:
return bad_request('Url must be provided in json format.')
if "original" not in request.json :
return bad_request('Url parameter not found.')
if "short_query" not in request.json:
return bad_request('Url parameter not found.')
original = request.json['original']
short = request.json['short_query']
if shorturl.query.filter_by(short_query = short).first() is not None:
return bad_request("Already Exists")
visits = 0
if original[:4] != 'http':
original = 'http://' + original
if not url_valid(original):
return bad_request('Provided url is not valid.')
url_db = shorturl(
short_query=short, original=original, visits=visits)
shortened_url = short
db.session.add(url_db)
db.session.commit()
return jsonify({'link': shortened_url}), 201
#app.route('/add', methods=['GET'])
def add_get():
if request.args.get('apikey') is not None and request.args.get('original') is not None and request.args.get('short_query') is not None:
api_key = request.args.get('apikey')
original = request.args.get('original')
short_query = request.args.get('short_query')
if apikey.query.filter_by(apikey = api_key).first() is None:
return errreq("Invalid API Key")
else:
if shorturl.query.filter_by(short_query=short_query).first() is not None:
return errreq("Already Exists")
else:
if original[:4] != 'http':
original = 'http://' + original
if not url_valid(original):
return bad_request('Provided url is not valid.')
url_db = shorturl(
short_query=short_query, original=original, visits=0)
db.session.add(url_db)
db.session.commit()
return jsonify({'link': short_query}), 200
else:
return bad_request("Nothing Provided")
#app.route('/view/<alias>', methods=['GET'])
def get_viewcount(alias):
if shorturl.query.filter_by(short_query=alias).first() is None:
return bad_request('Unknown alias.')
else:
return jsonify({'visits':shorturl.query.filter_by(short_query=alias).first().visits}),200
#app.route('/<alias>', methods=['GET'])
def get_shortened(alias):
if shorturl.query.filter_by(short_query=alias).first() is None:
return bad_request('Unknown alias.')
visits = shorturl.query.filter_by(short_query=alias).first().visits
url_db = shorturl.query.filter_by(short_query=alias).first()
url_db.visits = visits + 1
db.session.commit()
url = shorturl.query.filter_by(short_query=alias).first().original
return redirect(url, code=302)
# From https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not#7160778
# Slightly modified to not use ftp.
regex = re.compile(
r'^(?:http)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
if __name__ == '__main__':
'''
if os.path.exists('./db.sqlite3'):
app.run(host="0.0.0.0", port=8000, debug=False)
else: '''
db.create_all()
app.run(host="0.0.0.0", port=8000, debug=False)
Here if I add api key in /appapi with key in query string, I can add the key in the database. But the key added in the database does not work after a couple of hours.
Thanks in advance.
I figured this out. It is because I have added db.create_all() inside the main function. Removing this just works.

Getting a view does not return a valid response error message on my flask chatbot [duplicate]

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 2 years ago.
Trying to create a whatsapp bot on Twilio that limits the number of requests a user can make within a 24 hour period.
However, when I send through a request I get this error message on ngrok
File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
This is what I see on my twilio console:
MESSAGE
Internal Server Error
and on my terminal:
File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
"The view function did not return a valid response. The"
Here is the code I wrote
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
import random
from pathlib import Path
from twilio.rest import Client
from datetime import datetime
import pytz
import re
app = Flask(__name__)
#this will store information about user session such as the time of user's first request and request counter
sessionStorage = {}
#addng user to session storage with current time and setting request counter to 0
time = datetime.now(pytz.timezone('Africa/Harare'))
counter = 0
def add_user(user):
sessionStorage[user] = {}
#time when first session starts
sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
sessionStorage[user][counter] = 0
#checking if user can perform a request and updating time if required
def request_check(user):
difference = sessionStorage[user][time] - datetime.now(pytz.timezone('Africa/Harare'))
#check if it has been 24 hours after first request, if so then reset request counter and set last request time to current time
sessionStorage[user][counter] = 0
sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
#if user requests exceed 5 then do not allow any more requests
if sessionStorage[user][counter] > 5:
return False
#in other cases allow user to continue requesting
return True
#function to increment request counter for current user
def increment_request_counter(user):
sessionStorage[user][counter] +=1
#app.route('/bot', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
#extract phone number from ngrok
number = request.values.get('From', '')
#remove non numerical values
cleaned_number = re.sub('[^0-9]', '', number)
msg = resp.message()
#create new user
add_user(user=cleaned_number)
responded = False
if request_check(user=cleaned_number):
if incoming_msg == 'help':
output = 'Introduction text.'
msg.body(output)
responded = True
if 'testing' in incoming_msg:
msg.body(cleaned_number)
responded = True
if 'a' in incoming_msg:
pre = 'More text
msg.body(pre)
responded = True
if 'b' in incoming_msg:
pre = 'Test text'
msg.body(pre)
responded = True
if 'c' in incoming_msg:
pre = 'I do not currently have any stats challanges, but will be adding a few soon.'
msg.body(pre)
responded = True
if not responded:
msg.body('Test message.')
return str(resp)
increment_request_counter(user=cleaned_number)
if __name__ == '__main__':
app.run(debug=True)
The problem started when I tried to add the logic to limit the number of requests a user can make within a 24 hour period
The problem is that you are not returning a response which flask thinks as a valid response. You can read more about responses in flask here.
So in your case add a return after all of your ifs under if request_check(user=cleaned_number): in bot() method. Also you should not return None. I think you are looking to return a json (just an advice).
For example:
#app.route('/bot', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
#extract phone number from ngrok
number = request.values.get('From', '')
#remove non numerical values
cleaned_number = re.sub('[^0-9]', '', number)
msg = resp.message()
#create new user
add_user(user=cleaned_number)
responded = False
if request_check(user=cleaned_number):
if incoming_msg == 'help':
output = 'Introduction text.'
msg.body(output)
responded = True
return "My Message"

Plaid API quickstart project error http://127.0.0.1:5000/get_access_token

I am trying to get started with the plaid API. I created my account to get the API keys and I have the quickstart project. I put my keys in the code(they are not applied in the code below) and when I run it I use the sandbox credentials. Unfortunately after the log in succeeds I always receive the same error when trying to receive the access token:
HTTP500: SERVER ERROR - The server encountered an unexpected condition
that prevented it from fulfilling the request.(XHR)POST -
http://127.0.0.1:5000/get_access_token
Here is the code:
import os
import datetime
import plaid
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
app = Flask(__name__)
# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY')
# Use 'sandbox' to test with Plaid's Sandbox environment (username:
user_good,
# password: pass_good)
# Use `development` to test with live users and credentials and `production`
# to go live
PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')
client = plaid.Client(client_id = PLAID_CLIENT_ID, secret=PLAID_SECRET,
public_key=PLAID_PUBLIC_KEY, environment=PLAID_ENV)
#app.route("/")
def index():
return render_template('index.ejs', plaid_public_key=PLAID_PUBLIC_KEY,
plaid_environment=PLAID_ENV)
access_token = None
public_token = None
#app.route("/get_access_token", methods=['POST'])
def get_access_token():
global access_token
public_token = request.form['public_token']
exchange_response = client.Item.public_token.exchange(public_token)
print ('public token: ' + public_token)
print ('access token: ' + exchange_response['access_token'])
print ('item ID: ' + exchange_response['item_id'])
access_token = exchange_response['access_token']
return jsonify(exchange_response)
#app.route("/accounts", methods=['GET'])
def accounts():
global access_token
accounts = client.Auth.get(access_token)
return jsonify(accounts)
#app.route("/item", methods=['GET', 'POST'])
def item():
global access_token
item_response = client.Item.get(access_token)
institution_response = client.Institutions.get_by_id(item_response['item']
['institution_id'])
return jsonify({'item': item_response['item'], 'institution':
institution_response['institution']})
#app.route("/transactions", methods=['GET', 'POST'])
def transactions():
global access_token
# Pull transactions for the last 30 days
start_date = "{:%Y-%m-%d}".format(datetime.datetime.now() +
datetime.timedelta(-30))
end_date = "{:%Y-%m-%d}".format(datetime.datetime.now())
try:
response = client.Transactions.get(access_token, start_date, end_date)
return jsonify(response)
except plaid.errors.PlaidError as e:
return jsonify({'error': {'error_code': e.code, 'error_message':
str(e)}})
#app.route("/create_public_token", methods=['GET'])
def create_public_token():
global access_token
# Create a one-time use public_token for the Item. This public_token can
be used to
# initialize Link in update mode for the user.
response = client.Item.public_token.create(access_token)
return jsonify(response)
if __name__ == "__main__":
app.run(port=os.getenv('PORT', 5000))
Update your code like
PLAID_CLIENT_ID = 'client_id'
PLAID_SECRET = 'secret'
PLAID_PUBLIC_KEY = 'key'
PLAID_ENV = 'sandbox'
the problem was solved by putting the credentials to the client.py-file which is being created while you install plaid

Parse Header in Post Call Python

I am using rest client in my mozilla browser to call an auth service.
When i pass my credentials in Body, i get an "auth-token" . I then set this token in the header in the browser HEADERS tab.
I have to parse this header which i am setting in the browser in my python script as a variable. Further, after getting this value in my script i have to authenticate the token for its validity.
However i am unable to get the tokens value in my script. My auth function is ready. I just have to fetch the token
How should i fetch this token value from the header ??
Code:
def check_authentication(auth):
print "Auth" , auth
chek_auth_url = ("http://10.168.2.161/auth/v/%s" % (auth))
auth = requests.get(chek_auth_url)
if auth.status_code == 200:
return True
I have to pass the token as a paramter in this function and call in this function in main for authentication.
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
#h['Access-Control-Allow-Headers'] = "Content-Type"
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
#app.route('/test', methods=['POST', 'OPTIONS'])
#crossdomain(origin='*', headers='Content-Type')
def get_storage():
*check_authentication is called here and token is passed as a parameter*
*if token is valid further task i hav to do*
if __name__ == '__main__':
app.run(host='192.168.56.1', port=8080, threaded=True)
Self-Help is the best help..
Finally i found a fix:
The token value is fetched in the variable tokenValue. I can now do my further coding.
tokenValue = request.headers.get("token")
if tokenValue == None:
return "x-auth-token not passed in header, please pass the token."
else:
print "Token passed is", tokenValue

Categories

Resources