How to develop a counter on Flask with python - python

A friend asked me to develop a counter on Flask with python that updates itself when someone enters a number in an input but I'm a real beginner.
My method was to create a text file that keeps the precedent count so I could print the count + the input.
But I have a 400 error : "Bad Request The browser (or proxy) sent a request that this server could not understand."
Below is the code I wrote so far
Thanks for your help!
from flask import Flask, request
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def index():
choice = ''
choice = int(request.form["choice"])
if request.method == "POST":
with open( "count.txt", "r" ) as f:
count = f.read()
output = """#Content-type: text/html\r\n\r\n
<html>
<center>
<p>The count is now : {count}</p>
</center>
</html>
""".format(count=count)
count = int(count)
with open( "count.txt", "w" ) as f:
f.write(str(count+choice) )
print(output)
else:
choice = input("Enter a number : ")
choice = int(choice)
if __name__ == "__main__":
app.run(debug=True)

To simplify you could just:
from flask import Flask
app = Flask(__name__)
counter = 1 #or whatever you want to start with
#app.route('/')
def main():
global counter
counter += 1
return str(counter)
So this code works - now you need to adapt the changes of yours to the file.
Btw for what do you need to store it in a .txt file?

Related

Chatting flask projects with pymongo

This is the first time t work with flask and pymongo. Anyone can tell my why and how to fix this problem ?
I had watched this video: https://www.youtube.com/watch?v=7Abxa0q4Vuk and use his code. However, it isn't work when i try to login.
It is a picture I captured when I tried to log in with an account had already register
This is the login_check code:
if(request.method == 'POST'):
req = request.form
req = dict(req)
print(req)
query = user_table.find({'uid', req['uid']})
flag = 0
temp = None
for x in query:
if(x['uid'] == req['uid']):
flag = 1
temp = x
break
if(flag == 1):
if(temp['password'] == req['password']):
return render_template('dashboard.html', uid = req['uid'])
else:
return render_template('invalid.html', message = 'incorrect password')
else:
return render_template('invalid.html', message = "User not registered")
return render_template('login.html')
This is the error:
filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

Creating User in Active-Directory in Flask dont work

I have a Flask Webserver running with a site where you can create a user in my Windows Active-Directory. If I run the script as a separate file and set the variables manually it works as it should. But when I try to use input from the website in my script in my Flask program it does not work. I get the following error code: pywintypes.com_error: (-2147352567, 'Exception error occurred.', (0, None, None, 0, -2147221020), None). I am wondering that outside of the Flask script, it works. When I replace all varibles with strings it doesn't work either. So it seems to me that my function has a problem with Flask.
My Python code is the following:
from flask import Flask, redirect, url_for, render_template, request
from pyad import *
app = Flask(__name__)
def replaceUmlauts(string):
string = string.replace('ü', 'u')
string = string.replace('ö', 'o')
string = string.replace('ä', 'a')
string = string.replace('Ü', 'U')
string = string.replace('Ö', 'O')
string = string.replace('Ä', 'A')
return string
def createUser(firstname,lastname):
initials = replaceUmlauts(firstname)[0:1] + replaceUmlauts(lastname)[0:1]
loginName = replaceUmlauts(lastname)[0:4].lower() + replaceUmlauts(firstname)[0:2].lower()
email = replaceUmlauts(firstname).lower() + "." + replaceUmlauts(lastname).lower() + "#my.domain"
pyad.set_defaults(ldap_server="my.domain", username="Administrator", password="mypassword")
ou = pyad.adcontainer.ADContainer.from_dn("ou=OU1, ou=OU2, ou=OU3, dc=my, dc=domain")
new_user = pyad.aduser.ADUser.create(loginName, ou, password="Secret123", optional_attributes={
"givenName": firstname,
"sn": lastname,
"displayName": firstname + " " + lastname,
"mail": email,
"initials": initials
})
return True
#app.route("/")
def home():
return render_template("index.html")
#app.route("/addUser", methods=["POST", "GET"])
def addUser():
if request.method == "POST":
firstname = request.form["firstname"]
lastname = request.form["lastname"]
department = request.form["category"]
passwort = request.form["password"]
if len(firstname) == 0:
return redirect(url_for("addUser", error="The first name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in firstname):
return redirect(url_for("addUser", error="The first name must not contain numbers!"))
exit(1)
elif len(lastname) == 0:
return redirect(url_for("addUser", error="The last name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in lastname):
return redirect(url_for("addUser", error="The last name must not contain numbers!"))
exit(1)
elif len(passwort) < 6:
return redirect(url_for("addUser", error="The password must not have less than 6 characters!"))
exit(1)
createUser(firstname,lastname)
else:
return render_template("addUser.html")
if __name__ == "__main__":
app.run(debug=True)
I fixed the error by importing the libary called pythoncom and add the initialize command in my function, like this:
import pythoncom
def createUser(firstname, lastname):
pythoncom.CoInitialize()
And yes, it is a problem between pyad and Flask

Overwrite a text file to update python HTML to change user password

I'm trying to complete this program I need to be able to update a password saved in txt file for a user already saved in the text file and I can't figure out how to do so.
Looking for help on tasks A-C
a. Password update Form – This Python form allows a previously registered user to reset their password after they have successfully logged in.
b. Authentication functions – These Python functions will check the following NIST SP 800-63B criteria are met upon password update:
Use the previous criteria for password length and complexity. (This work should already be
done.)
Compare the prospective secrets against a list that contains values known to be commonly-
used, expected, or compromised (Provided as CommonPasswords.txt).
If the chosen secret is found in the list, the application SHALL advise the subscriber that they
need to select a different secret.
c. Logger – Create a log to log all failed login attempts. The Log should include date, time and IP
address.
from datetime import datetime
from flask import Flask, flash, redirect, render_template, request, session, url_for
import re
from wtforms import Form, PasswordField
from wtforms.validators import DataRequired
app = Flask(__name__)
def validate_password(password):
SpecialSym = ['$', '#', '#', '%', '!', '&', '*']
val = True
if len(password) < 6:
print('length should be at least 6')
val = False
if len(password) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in password):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in password):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in password):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in password):
print('Password should have at least one of the symbols $##')
val = False
if val:
return val
else:
return False
now = datetime.now() # current date and time
date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
# each route for the pages
#app.route("/")
def welcome():
"""the welcome page"""
return render_template("welcome.html")
#app.route("/home")
def home():
"""the home page"""
if not session.get('logged_in'):
return render_template('login.html')
else:
return redirect('home')
#app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("register.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("SUCCESSFUL REGISTERED *")
return render_template("homepage.html", error="SUCCESSFUL REGISTERED *")
else:
return render_template("register.html")
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "r")
data = f.readlines()
f.close()
data = [x.split() for x in data]
for item in data:
if request.form['email'] == item[0].strip() and request.form['password'] == item[1].strip():
session['logged_in'] = True
return render_template('homepage.html')
else:
error = "Wrong Credentials"
return render_template("login.html", error=error)
else:
return render_template("login.html")
#app.route("/reset", methods=['GET', 'POST'])
def reset():
"""reset page"""
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("reset.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("Password Reset *")
return render_template("reset.html", error="Password Reset *")

Flask project works locally but not in Heroku [duplicate]

This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 2 years ago.
I made this simple chat bot in Python and Flask. It works perfectly when I run it in a local server but I uploaded it to Heroku (my first time uploading) and some options only work sometimes.
In the above image, entering 3 should prompt the app to ask user for a city name but it doesn't most of the times.
#imports
import requests
from flask import Flask, render_template, request
app = Flask(__name__)
import random
newsApiKey = 'c0f976e7caac4b608d84c4546e0b892c'
isGreeted = False
isThree = False
def getRequest(location):
global newsApiKey
url = "http://newsapi.org/v2/everything?q={} AND +corona AND english&qInTitle=+corona&language=en&from=2020-03-25&sortBy=relevancy&apiKey={}".format(location,newsApiKey)
r = requests.get(url)
return r
def getGreeting():
greets = ['Hello there General Kenobi!', 'Hi there!', 'Hi, how are you?']
return random.choice(greets)
#define app routes
#app.route("/")
def index():
return render_template("index.html")
#app.route("/get")
#function for the bot response
def get_bot_response():
global isGreeted
global isThree
userText = request.args.get('msg')
# return str(englishBot.get_response(userText))
responseMessage = ""
if userText in ['Hi!', 'Hello!', 'Hi'] and isGreeted == False:
responseMessage = getGreeting() + "\n\nChoose an option from below menu:\n\n1 - What is Covid-19?\n\n2 - What are the symptoms of Covid-19?\n\n3 - Local news about Covid-19\n\n4 - What should I do?"
isGreeted = True
elif userText in ['1','2','3','4'] and isGreeted:
if userText == '1':
responseMessage = "Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus."
elif userText == '2':
responseMessage = "Common symptoms include fever, tiredness, dry cough. Other symptoms include shortness of breath, aches and pains, sore throat, diarrhoea, runny nose. People with mild symptoms should try self isolating and others should seek medical attention."
elif userText == '3' and isThree == False:
responseMessage = 'Enter your city name'
isThree = True
elif userText == '4':
responseMessage = 'Stay at home. If you plan to go outside, avoid using public transportation. Seek medical attention if you have trouble breathing, pain in chest, bluish lips. Cover your face with an N95 mask. Clean your hands often.'
elif isThree:
r = getRequest(userText).json()
# print(r)
isThree = False
counter = 0
for article in r['articles']:
if counter != 3:
responseMessage += article['title'] + '\n' + article['description'] + '\n\n'
counter = counter + 1
else:
break
return responseMessage
if __name__ == "__main__":
app.run()
Does it have anything to do with the way I handle responses? Or the fact I am using global variables? If yes, what is the better way to do this? Thank you in advance.
I would suggest using flask-socketio for realtime comunication especially for chat. It's a wrapper for socket-io
https://flask-socketio.readthedocs.io/en/latest/
In python
import flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on('message')
def handle_message(data):
#handle message
if __name__ == "__main__":
socketio.run(app)
On client
var socket = io();
socket.emit('message', { "msg": "something"});
Also to check what's going on ur heroku server use this
heroku logs --tail

Running a continous while loop in python along with Flask app

I am working on writing a code in raspberry pi using python where i want the user to input the set temperature and fan mode via web page i'm using flask for that and the values are returned successfully but i also want to run a infinite while loop along with the flask app which will compare the set temperature with the current temperature from a sensor.. how do i achieve this without interrupting the flask app?
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
import time
temp = ""
t = ""
fan_High = 0
fan_Med = 0
fan_Low =0
fanspeed = ""
app = Flask(__name__)
#app.route('/form', methods=['POST'])
def aziz():
global temp ,fanspeed
fanspeedlocal = ''
if request.form['settemp'] != "":
temp = request.form['settemp']
templocal = temp
else:
templocal = temp
if request.form['speed'] == "null":
fanspeedlocal = fanspeed
else:
if request.form['speed'] == "High":
fan_Med = False
fan_Low = False
fan_High = True
fanspeed = "High"
fanspeedlocal = fanspeed
elif request.form['speed'] == "Med":
fan_High = False
fan_Low = False
fan_Med = True
fanspeed = "Medium"
fanspeedlocal = fanspeed
elif request.form['speed'] == "Low":
fan_High = False
fan_Med = False
fan_Low = True
fanspeed = "Low"
fanspeedlocal = fanspeed
print 'Settemp = %s' %temp
print 'fanspeed = %s' %fanspeed
return render_template('Output.html',temp=templocal,currtemp=strct,time=t,fanspeed=fanspeedlocal
#app.route('/')
def start():
global t , fanspeed
t = time.strftime("%H:%M:%S")
return render_template('Start.html',temp=temp,currtemp=strct,time=t,fanspeed=fanspeed)
if __name__ == '__main__':
app.debug = False
app.run(host = '192.168.1.101')
var = 1
while var == 1:
inttemp = int(temp)
if currtemp >= inttemp:
#set GPIO to high
else:
#set GPIO to low
if fanspeed == 'High':
#set GPIO to high
elif fanspeed == 'Med':
#set GPIO to high
elif fanspeed == 'LOW':
#set GPIO to high
time.sleep(10)
I would just use cron. You could use a simple script that looks something like this:
#!/usr/bin/python3
# or python, if that's your thing
import requests
def get_sensor_data():
'''Presumably you know what actually goes here.'''
return {'temperature': 5, 'fan speed': 'no, three, sir'}
requests.post('http://example.com/update?api_key=12345', data=get_sensor_data())
Then just setup cron to run it every 60s or less. Now your Flask app just gets requests from your script that updates the data, while your page updates.
Alternatively, you could just setup a Flask #app.before_request decorator that will just request the necessary data and attach it to the special g object.
If it's quick (<250ms) to read the data, I'd probably do the latter. If it takes more than 250ms, then I'd probably make cron do it.
I think, you just input the while command inside the:
#app.route('/')
def start():
or in some place which you like

Categories

Resources