Session is None in other Request - python

I am using flask to build up an api but session in requests is NONE when i am running this from html files and sending data with jquery. When i am sending with Postman the api is running normally. I use first /signup method and after /map in this is None. Can you help me? Have you any idea
import pymysql
from pymysql import install_as_MySQLdb
from flask import Flask, request, jsonify, session, g
from flask_session import Session
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'filesystem'
cors = CORS(app,allow_headers='Content-Type')
app.config['PROPAGATE_EXCEPTIONS'] = False
Session(app)
db = pymysql.connect("localhost", "root", "", "thesis")
#app.route('/signUp', methods=['GET','POST'])
def signUp():
#session.pop('userId', None)
data = request.get_json()
print(data)
cursor = db.cursor()
email = data['email']
password = data['pass']
fname=data['firstName']
lname=data['lastName']
cid=data['type']
points="0"
print(email)
print(password)
query = "SELECT * FROM users WHERE email=%s;"
cursor.execute(query, email)
rows = cursor.fetchall()
print(len(rows))
# print(rows[0])
if len(rows) == 0:
query = "INSERT INTO users(email,password,fname,lname,cid,points)VALUES(%s,%s,%s,%s,%s,%s);"
cursor.execute(query, (email,password,fname,lname,int(cid),int(points)))
db.commit()
query = "SELECT * FROM users WHERE email=%s;"
a=cursor.execute(query, email)
print(a)
rows = cursor.fetchall()
print(rows[0])
if len(rows) == 1:
for results in rows:
session['userId']=str(results[0])
print(session['userId'])
return jsonify(fname=fname, lname=lname,cid=cid)
else:
return jsonify(fname="", lname="")
else:
return jsonify(fname="", lname="")
#app.route('/map', methods=['POST','GET'])
#cross_origin(origin='*',headers=['Content-Type','Authorization'])
def map():
print(session.get('userId'))
data = request.get_json()
print(data)
cursor = db.cursor()
lat= data['lat']
lon = data['lon']
query = "UPDATE users SET lon=%s, lat=%s WHERE uid=%s;"
cursor.execute(query,(lon,lat,session.get('userId')))
db.commit()
return "hello"
if __name__ == "__main__":
app.run(debug=True)

Related

internal server error after submitting a form flask,sqlite3 [duplicate]

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed last year.
I inserted new record from the form, the data will be successfully added into database, but it will show an error page "INTERNAL SERVER ERROR", if I manually back to my form page and refresh i can see the inserted data, but i want it refresh it self and don't show the error page, how to do that?
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
db_name = 'crm.db'
#app.route('/')
def index():
title = "主页"
return render_template("index.html", title = title)
#app.route('/company', methods = ['POST','GET'])
def company():
if request.method == 'GET':
title = "公司"
company_db = query_company()
return render_template("company.html", title = title, company_db = company_db)
else:
insert_company()
def query_company():
connection = sqlite3.connect(db_name)
c = connection.cursor()
c.execute("""SELECT * FROM company""")
company_db = c.fetchall()
return company_db
def insert_company():
connection = sqlite3.connect(db_name)
c = connection.cursor()
query = 'INSERT INTO company(company_full_name, company_short_name) VALUES(?,?)'
cfn = request.form.get("cfn")
csn = request.form.get("csn")
company_info = (cfn,csn)
c.execute(query, company_info)
connection.commit()
connection.close()
if __name__ == '__main__':
app.run(debug = True)
Change the company function to ...
def company():
if request.method == 'POST':
insert_company()
title = "公司"
company_db = query_company()
return render_template("company.html", title = title, company_db = company_db)
This way the new data will first be inserted and then all rows will be automatically refreshed

Im trying to test my forms in my flask app using unittest, Am I doing the right way?

I wanna test my app using the unittest package. specifically I'm trying to test my forms. I'm having a hard time testing the post request on how to get the data from my forms and posting it
my reference:
https://realpython.com/python-testing/#more-advanced-testing-scenarios
my test.py code
from app import app
import unittest
class FlaskTestCase(unittest.TestCase):
def test_add(self):
tester = app.test_client(self)
response = tester.post('/Search/add', data=dict(fn =
"Emmanuel Ever", ln = "Telewik", email =
"everlopeztelewik#gmail.com", phone = 0912312311,
address = "ILIGAN"),
follow_redirect = True
)
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
the function I'm going to test in app.py
#app.route("/Search/add", methods=['POST'])
def new():
if request.method == 'POST':
fn = request.form['fn']
ln = request.form['ln']
email = request.form['email']
phone = request.form['phone']
address = request.form['address']
conn = psycopg2.connect("dbname = 'test_db3' user = 'postgres'
password = 'shizzle7' host = 'localhost' port = '5432'")
cur = conn.cursor()
cur.execute("INSERT into user2 values(Default, %s, %s, %s, %s,
%s)",(fn,ln,email,phone,address))
conn.commit()
conn.close()
return redirect('/Search')
return render_template('index.html')

Error 500 when running python flask application with xampp

I am trying to run a flask application with xampp but I can't run it on the web server.
I have added .py to Addhandler in /opt/lampp/etc/httpd.conf and at the top of all my scripts I added this: #!/usr/bin/python
#!/usr/bin/python
import sqlite3, os, hashlib
from flask import Flask, jsonify, render_template, request, g
app = Flask(__name__)
app.database = "sample.db"
#app.route('/')
def index():
return render_template('login.html')
#API routes
#app.route('/api/v1.0/storeLoginAPI/', methods=['POST'])
def loginAPI():
if request.method == 'POST':
uname,pword = (request.json['username'],request.json['password'])
g.db = connect_db()
cur = g.db.execute("SELECT * FROM employees WHERE username = '%s' AND password = '%s'" %(uname,pword))
if cur.fetchone():
result = {'status': 'success'}
else:
result = {'status': 'fail'}
g.db.close()
return jsonify(result)
#app.route('/api/v1.0/storeAPI', methods=['GET', 'POST'])
def storeapi():
if request.method == 'GET':
g.db = connect_db()
curs = g.db.execute("SELECT * FROM shop_items")
cur2 = g.db.execute("SELECT * FROM employees")
items = [{'items':[dict(name=row[0], quantity=row[1], price=row[2]) for row in curs.fetchall()]}]
empls = [{'employees':[dict(username=row[0], password=row[1]) for row in cur2.fetchall()]}]
g.db.close()
return jsonify(items+empls)
elif request.method == 'POST':
g.db = connect_db()
name,quan,price = (request.json['name'],request.json['quantity'],request.json['price'])
curs = g.db.execute("""INSERT INTO shop_items(name, quantitiy, price) VALUES(?,?,?)""", (name, quan, price))
g.db.commit()
g.db.close()
return jsonify({'status':'OK','name':name,'quantity':quan,'price':price})
#app.route('/api/v1.0/storeAPI/<item>', methods=['GET'])
def searchAPI(item):
g.db = connect_db()
#curs = g.db.execute("SELECT * FROM shop_items WHERE name=?", item) #The safe way to actually get data from db
curs = g.db.execute("SELECT * FROM shop_items WHERE name = '%s'" %item)
results = [dict(name=row[0], quantity=row[1], price=row[2]) for row in curs.fetchall()]
g.db.close()
return jsonify(results)
#app.errorhandler(404)
def page_not_found_error(error):
return render_template('error.html', error=error)
#app.errorhandler(500)
def internal_server_error(error):
return render_template('error.html', error=error)
def connect_db():
return sqlite3.connect(app.database)
# Create password hashes
def hash_pass(passw):
m = hashlib.md5()
m.update(passw)
return m.hexdigest()
if __name__ == "__main__":
#create database if it doesn't exist yet
if not os.path.exists(app.database):
with sqlite3.connect(app.database) as connection:
c = connection.cursor()
c.execute("""CREATE TABLE shop_items(name TEXT, quantitiy TEXT, price TEXT)""")
c.execute("""CREATE TABLE employees(username TEXT, password TEXT)""")
c.execute('INSERT INTO shop_items VALUES("water", "40", "100")')
c.execute('INSERT INTO shop_items VALUES("juice", "40", "110")')
c.execute('INSERT INTO shop_items VALUES("candy", "100", "10")')
c.execute('INSERT INTO employees VALUES("itsjasonh", "{}")'.format(hash_pass("badword")))
c.execute('INSERT INTO employees VALUES("theeguy9", "{}")'.format(hash_pass("badpassword")))
c.execute('INSERT INTO employees VALUES("newguy29", "{}")'.format(hash_pass("pass123")))
connection.commit()
connection.close()
app.run()
When I run my apache server and try to access localhost/sql.py I get an "Error message:
End of script output before headers: sql.py

OperationalError: no such table: books on python anywhere

I have a file structure on python anywhere as :
flaskhost(folder) which contains :
app.py
books.db
app.py contains -:
import flask
from flask import request, jsonify
import sqlite3
app = flask.Flask(__name__)
app.config["DEBUG"] = True
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
#app.route('/', methods=['GET'])
def home():
return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''
#app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM books;').fetchall()
return jsonify(all_books)
#app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
#app.route('/api/v1/resources/books', methods=['GET'])
def api_filter():
query_parameters = request.args
id = query_parameters.get('id')
published = query_parameters.get('published')
author = query_parameters.get('author')
query = "SELECT * FROM books WHERE"
to_filter = []
if id:
query += ' id=? AND'
to_filter.append(id)
if published:
query += ' published=? AND'
to_filter.append(published)
if author:
query += ' author=? AND'
to_filter.append(author)
if not (id or published or author):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
if __name__ == '__main__':
app.run()
I am trying to follow this tutorial
https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
my site is hosted at :
http://vivanks.pythonanywhere.com
But when I call api by
http://127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis
It show me error :
sqlite3.OperationalError: no such table: books
Any help how to fix this and host app on pythonanywhere.com ?
P.S On my local machine it's working perfectly fine
On Pythonanywnere, When pointing to content other than templates or static files (stored in their own proper directories, accessible by flask), you have to provide the full path:
conn = sqlite3.connect('/home/your_username/flaskhost/books.db')

Python Post data through command line

I am struggling with this a lot. Have gone through the requests API documentation, but not able to execute this perfectly.
I have written a python script, which is meant to GET, POST',and the remaining REST operations through a command line.GETworks fine, and any request from thelocalhost` url gets retrieved.
However, I am unable to POST a new data. For example, the GET method is issued like this:
request.py -r get -f 1 -u http://127.0.0.1:5002/user
and the userID 1's data get displayed in JSON format. user is the name of the database, which contains these operations.
Similarly, I would like to post a new data in JSON format
I tried this command, but I am receiving the error
request.py -r get -f 7 -u http://127.0.0.1:5002/user {'user':'abc','email':xyz#abc.com}
getAddrInfoFailed
The following is the code for creating database and also the requests
from flask import Flask, request
from flask_restful import Resource, Api
import sqlite3
import re
app = Flask(__name__)
api = Api(app)
def validate_email(email):
match = re.search('^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$', email)
if match:
return True
else:
return False
def validate_username(username):
match = re.search('^[A-Za-z0-9_-]{3,20}$', username)
if match:
return True
else:
return False
def validate_id(id):
if id.isdigit():
return True
else:
return False
class Users(Resource):
def get(self, id):
try:
conn = sqlite3.connect('curd.db')
cursor = conn.cursor()
if validate_id(id):
query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
row = query.fetchone()
if row:
return {'item': {'id': row[0], 'username': row[1], 'email': row[2]}},200
else:
return {'MESSAGE': 'USER NOT FOUND'}, 404
else:
return {'MESSAGE': 'INVALID INPUT'}, 400
except:
conn.rollback()
finally:
conn.commit()
conn.close()
def post(self, id):
try:
conn = sqlite3.connect('curd.db')
cursor = conn.cursor()
usr = request.get_json()
username = usr['username']
email = usr['email']
if validate_id(id) is True and validate_username(username)is True and validate_email(email) is True:
query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
row = query.fetchone()
if row:
return {'MESSAGE': 'USER ID ALREADY EXISTS'}, 400
else:
cursor.execute("INSERT INTO user(id, username, email) VALUES(?,?,?)", [id, username, email])
return {'response': 'Success'},201
else:
return {'MESSAGE': 'INVALID INPUT'}, 400
except:
conn.rollback()
finally:
conn.commit()
conn.close()
def put(self, id):
try:
conn = sqlite3.connect('curd.db')
cursor = conn.cursor()
usr = request.get_json()
updated_name = usr['username']
updated_email = usr['email']
if validate_id(id) and validate_username(updated_name) and validate_email(updated_email):
query = cursor.execute("SELECT * FROM user WHERE id=?", [int(id), ])
row = query.fetchone()
if row:
cursor.execute("UPDATE user SET username = '" + str(updated_name) + "',email = '" + str(updated_email) + "' WHERE id = %d" % int(id))
return {'response': 'Success'},200
else:
return {'MESSAGE': 'USER NOT FOUND'}, 404
else:
return {'MESSAGE': 'INVALID INPUT'}, 400
except:
conn.rollback()
finally:
conn.commit()
conn.close()
def delete(self, id):
try:
conn = sqlite3.connect('curd.db')
cursor = conn.cursor()
if validate_id(id):
query = cursor.execute("SELECT * FROM user WHERE id=?", [id, ])
row = query.fetchone()
if row:
conn.execute("DELETE FROM user WHERE id = %d" % int(id))
return {'response': 'Success'},200
else:
return {'MESSAGE': 'USER NOT FOUND'}, 404
else:
return {'MESSAGE': 'INVALID INPUT'}, 400
except:
conn.rollback()
finally:
conn.commit()
conn.close()
api.add_resource(Users,'/user/<string:id>',methods=['GET','POST','PUT','DELETE'])
if __name__ == '__main__':
app.run(port=5002, debug=True)
requests.py
import requests
import json
import sys
from optparse import OptionParser, make_option
if len(sys.argv) <= 1:
print('Need at least 1 argument.')
print("Add -h for Help")
sys.exit(1)
parser = OptionParser()
parser.add_option('-r', '--request', help="Request Type['GET','POST','PUT','DELETE']",default="")
parser.add_option('-f', '--id', help='id')
parser.add_option('-u', '--url', help="URL String",default="")
(options, args) = parser.parse_args()
print("ID = "+options.id)
print("Request Type = "+options.request)
print("Request URL = "+options.url)
url = options.url+"/"+options.id
data = ''
payload= {'key1':'value1','key2':'value2'}
if options.request == "get":
response = requests.get(url, data=data)
elif options.request=="post":
response = requests.post(url, params=payload)
else:
print("Invalid Request..!!")
print(response.text)

Categories