Python : No module named 'flask' - python

So i've been stuck on this problem for a while now. For one file I have it is working and it is allowing me to use the flask framework. with this code.
from flask import Flask, render_template
from flask import request
from flask import *
from datetime import datetime
from functools import wraps
import time
import csv
app = Flask(__name__)
app.secret_key ='lukey'
#displays index page
#app.route('/')
def home():
return render_template('index.html')
#displays welcome page
#app.route('/welcome')
def welcome():
return render_template('welcome.html')
#allows user to login
#app.route('/log', methods=['GET','POST'])
def log():
error = None
if request.method == "POST":
if request.form['user'] != 'admin' or request.form['pass'] != 'admin':
error = "Invalid credentials"
else:
session['logged_in'] = True
return redirect (url_for('welcome'))
return render_template('log.html', error=error)
#allows user to logout
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('you were logged out')
return redirect (url_for('log'))
#function to check if admin is logged in
def login_required(test):
#wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('you need to login before using admin tools')
return redirect(url_for('log'))
return wrap
#Displays map
#app.route('/map')
def map():
return render_template('map.html')
#Displays gallery
#app.route('/gallery')
def gallery():
return render_template('gallery.html')
#Allows users to view previous bookings
#app.route('/bookings', methods = ['GET'])
def bookings():
bookingsFile ='static\\bookings.csv'
data = readFile(bookingsFile)
return render_template('bookings.html', data=data)
#Allows user to request for a booking
#app.route('/addBookings', methods = ['POST'])
def addBookings():
bookingsFile = 'static\\bookings.csv'
data = readFile(bookingsFile)
bookingName = request.form[('name')]
bookingEmail = request.form[('email')]
bookingDate= request.form[('date')]
#Converts the date string to unix timestamp
bookingDateUnix = time.mktime(datetime.strptime(request.form[('date')], "%Y-%m-%d").timetuple())
numberOfDays = request.form[('days')]
#calculates the end date in unix form
endDateUnix = int(numberOfDays)*24*60*60+int(bookingDateUnix)
#converts the unix form end date to string
newDate = datetime.fromtimestamp(int(endDateUnix)).strftime('%Y-%m-%d')
#Calculates the price of the users stay
price = int(numberOfDays) * 200
#Will be changed by admin to confirm bookings
hasBeenBooked = 'Awaiting confirmation'
bookingsFile ='static\\bookings.csv'
for row in data:
prevBookingDateUnix = row[7]
prevEndDateUnix = row[8]
#Testing no double bookings
if row[2] == bookingDate or row[6] == newDate:
flash('This time has already been allocated')
return redirect(url_for('bookings'))
#Testing there are no crossover points
elif float(prevBookingDateUnix) < bookingDateUnix and float(prevEndDateUnix) < bookingDateUnix and bookingDateUnix < endDateUnix:
flash('valid input')
else:
flash('invalid input')
return redirect(url_for('bookings'))
#parameters parsed from input
newEntry =[bookingName, bookingEmail, bookingDate, numberOfDays, hasBeenBooked, price, newDate, bookingDateUnix, endDateUnix]
data.append(newEntry)
writeFile(data, bookingsFile)
return render_template('bookings.html', data=data)
#allows viewing of comments in csv file
#app.route('/comments', methods = ['GET'])
def comments():
commentsFile = 'static\\comments.csv'
data = readFile(commentsFile)
return render_template('comments.html', data=data)
#adding comments to csv file
#app.route('/addComments', methods = ['POST'])
def addComments():
# add an entry to the data
#read the data from file
commentsFile = 'static\\comments.csv'
data = readFile(commentsFile)
#add the new entry
commentorsName = request.form[('commentorsName')]
comment = request.form[('comment')]
commentDate = datetime.now().strftime("%Y-%m-%d / %H:%M")
newEntry = [commentorsName, comment, commentDate]
data.append(newEntry)
#save the data to the file
writeFile(data, commentsFile)
return render_template('comments.html', data=data)
#Ensures the administrator is logged in before comments are deleted
#app.route('/deleteComments', methods = ['POST'])
#login_required
def deleteComments():
f = open('static\\comments.csv', 'w')
f.truncate()
f.close()
return render_template('comments.html')
#Ensures the administrator is logged in before bookings are deleted
#app.route('/deleteBookings', methods = ['POST'])
#login_required
def deleteBookings():
f = open('static\\bookings.csv', 'w')
f.truncate()
f.close()
return render_template('bookings.html')
def readFile(aFile):
#read in 'aFile'
with open(aFile, 'r') as inFile:
reader = csv.reader(inFile)
data = [row for row in reader]
return data
def writeFile(aList, aFile):
#write 'aList' to 'aFile'
with open(aFile, 'w', newline='') as outFile:
writer = csv.writer(outFile)
writer.writerows(aList)
return
if __name__ == '__main__':
app.run(debug = True)
But with this code it throws the error. No module named 'flask'
#!/usr/bin/python3.4
#
# Small script to show PostgreSQL and Pyscopg together
#
from flask import Flask, render_template
from flask import request
from flask import *
from datetime import datetime
from functools import wraps
import time
import csv
import psycopg2
app = Flask(__name__)
app.secret_key ='lukey'
def getConn():
connStr=("dbname='test' user='lukey' password='lukey'")
conn=psycopg2.connect(connStr)
return conn
#app.route('/')
def home():
return render_template(index.html)
#app.route('/displayStudent', methods =['GET'])
def displayStudent():
residence = request.args['residence']
try:
conn = None
conn = getConn()
cur = conn.cursor()
cur.execute('SET search_path to public')
cur.execute('SELECT stu_id,student.name,course.name,home_town FROM student,\
course WHERE course = course_id AND student.residence = %s',[residence])
rows = cur.fetchall()
if rows:
return render_template('stu.html', rows = rows, residence = residence)
else:
return render_template('index.html', msg1='no data found')
except Exception as e:
return render_template('index.html', msg1='No data found', error1 = e)
finally:
if conn:
conn.close()
##app.route('/addStudent, methods =['GET','POST']')
#def addStudent():
if __name__ == '__main__':
app.run(debug = True)
I feel like the problem is going to be something to do with the versions of python/flask/pip i'm using. Any ideas thank you.

Your Python version is 2.X.
Take a look at this question and its answers.
Your best bet is to use virtualenv, as it makes handling package versions very simple. The accepted answer includes the proper command prompt commands if you want to use Python 3 for this app:
virtualenv -p C:\Python34\python.exe py3env
py3env\Scripts\activate
pip install package-name

I would recommend using Anaconda. Download, install, then run:
conda install flask
And you're done.

Related

List of chooses depending on user permissions

I'm building simple app on streamlit. I'm struggling with making list of chooses depending on user permissions.
utils.py
Dict with pages:
pages = {
"Start": start_page,
"Test kabli": cable_test_page,
"ARP": arp_page,
"FGRestart": fg_restart_page,
"MACTable": mac_table_page,
"PingGateWAN": ping_gate_wan_page,
"PInterface": psyhical_interface_page,
"RoutingTable": routing_table_page,
"TestŁączaWWAN(LTE)": wan_lte_test_page,
"WanMAC": wan_mac_page,
"TestŁączaWAN": wan_test_page,
"ResetPortów": reset_poe_page,
"RestartSwitcha": switch_restart_page,
}
Function for selecting items from a list
def select_page(ssh):
page = st.selectbox("Select item", tuple(pages.keys()))
pages[page](ssh)
Permissions to each item in a list are made like this:
permissions = {
'cable_diag': ["user1","user2","user3"],
'ping':[ "user1","user2","user3"],
'arp': ["user1","user2","user3"],
'fgrestart':["user1","user2","user3"],
'mactable':["user1","user2","user3"],
'Pinterface':["user1","user2","user3"],
'poe':["user1","user2","user3"],
'routingtable':["user1","user3"],
'srestart':["user1","user2","user3"],
'lte':["user2","user3"],
'wanmac':["user1","user2","user3"],
'wan':["user2","user3"],}
def decorator(func):
#wraps(func)
def wrapper(*args, **kwargs):
if st.session_state["username"] in permissions[module_name]:
print('Accessed')
return func(*args, **kwargs)
else:
st.text('ACCESS DENIED')
return wrapper
return decorator
All file with page have assigned role like this:
#has_role('page_name')
It's working but i want that if user1 don't have permissions to site 'wan' i also want that he will not be able to see this page in the list. I really don't have idea how to solve it
Full utils.py
import streamlit as st
import pandas as pd
import paramiko
from permissions import permissions
from modules.streamlit.pages.cable_test import cable_test_page
from modules.streamlit.pages.arp import arp_page
from modules.streamlit.pages.fg_restart import fg_restart_page
from modules.streamlit.pages.mac_table import mac_table_page
from modules.streamlit.pages.ping_gate_wan import ping_gate_wan_page
from modules.streamlit.pages.psyhical_interface import psyhical_interface_page
from modules.streamlit.pages.routing_table import routing_table_page
from modules.streamlit.pages.switch_restart import switch_restart_page
from modules.streamlit.pages.wan_lte_test import wan_lte_test_page
from modules.streamlit.pages.wan_mac import wan_mac_page
from modules.streamlit.pages.wan_test import wan_test_page
from modules.streamlit.pages.reset_poe import reset_poe_page
from modules.streamlit.pages.start import start_page
from modules.streamlit.pages.test import test_page
pages = {
"Start": start_page,
"Test kabli": cable_test_page,
"ARP": arp_page,
"FGRestart": fg_restart_page,
"MACTable": mac_table_page,
"PingGateWAN": ping_gate_wan_page,
"PInterface": psyhical_interface_page,
"RoutingTable": routing_table_page,
"TestŁączaWWAN(LTE)": wan_lte_test_page,
"WanMAC": wan_mac_page,
"TestŁączaWAN": wan_test_page,
"ResetPortów": reset_poe_page,
"RestartSwitcha": switch_restart_page,
}
custom_options = {"sideBar": False, "enableCellTextSelection": True}
#st.cache
def load_markets_xls():
df = pd.read_excel("path",
index_col=None, engine="openpyxl")
return df
def choose_market(df):
shop_number = st.text_input('Number', '')
if shop_number:
df = df[df["Host_Name"].notna()]
df['Host_Name'] = df['Host_Name'].astype(int).astype(str)
try:
single_row = df.loc[df['Host_Name'] == shop_number].to_dict('records')[0]
ip = single_row['ip']
return ip
except IndexError:
st.text("No found ")
def connect_to_market(ssh,market_ip):
print(market_ip)
try:
ssh.connect(hostname=str(market_ip), port=22, username='user',
password='password', allow_agent=False, timeout=None, compress=False)
st.text('Connected!')
return True
except Exception as e:
st.text('----- ')
return False
def select_page(ssh):
page = st.selectbox("Choose", tuple(pages.keys()))
pages[page](ssh)
Full permissions.py:
from functools import wraps
import streamlit as st
import pandas as pd
import paramiko
permissions = {
'cable_diag': ["user1","user2","user3"],
'ping':[ "user1","user2","user3"],
'arp': ["user1","user2","user3"],
'fgrestart':["user1","user2","user3"],
'mactable':["user1","user2","user3"],
'Pinterface':["user1","user2","user3"],
'poe':["user1","user2","user3"],
'routingtable':["user1","user3"],
'srestart':["user1","user2","user3"],
'lte':["user2","user3"],
'wanmac':["user1","user2","user3"],
'wan':["user2","user3"],}
def has_role(module_name):
def decorator(func):
#wraps(func)
def wrapper(*args, **kwargs):
if st.session_state["username"] in permissions[module_name]:
print('jest dostep')
return func(*args, **kwargs)
else:
st.text('ACCESS DENIED!')
return wrapper
return decorator```
app.py:
import streamlit as st
import pandas as pd
import paramiko
import streamlit_authenticator as stauth
from utils import load_markets_xls, choose_market, connect_to_market, select_page
from cred import hashed_passwords , names, usernames
from PIL import Image
import base64
ssh = paramiko.SSHClient()
# ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hide_menu_style = """
<style>
#MainMenu {visibility: hidden;}
</style>
"""
custom_options = {"sideBar": False, "enableCellTextSelection": True}
def main():
st.set_page_config(page_title='Market Tests', layout="wide")
st.markdown(hide_menu_style, unsafe_allow_html=True)
authenticator = stauth.Authenticate(names,usernames,hashed_passwords, 'cookie','some_key', cookie_expiry_days=0)
col1, col2, col3 = st.columns(3)
with col1:
st.write(' ')
with col2:
image = Image.open('path')
st.image(image)
with col3:
st.write(' ')
name, authentication_status, username = authenticator.login('Panel Logowania','main')
if authentication_status:
authenticator.logout('Logout', 'main')
data_load_state = st.text('Loading data...')
df = load_markets_xls()
data_load_state.text('Markets loaded!')
market_ip = choose_market(df)
if (market_ip):
if connect_to_market(ssh, market_ip):
select_page(ssh)
elif authentication_status == False:
st.error('Username/password is incorrect')
elif authentication_status == None:
st.warning('Please enter your username and password')
def refresh_data():
st.legacy_caching.clear_cache()
raise st.script_runner.RerunException(st.script_request_queue.RerunData(None))
if __name__ == "__main__":
main()
sample page:
import streamlit as st
from permissions import has_role
custom_options = {
"enableCellTextSelection": True,
"sideBar":True
}
#has_role('arp')
def arp_page(ssh):
st.title('ARP')
stdin, stdout, stderr = ssh.exec_command("get system arp")
for line in iter(stdout.readline, ""):
st.text(line)

Issue implementing the python code around cx_Oracle library

I am getting an error while implementing the below code:
'''
from pandas.core.frame import DataFrame
import cx_Oracle
import pandas as pd
import sys
class IFTDataCore:
def __init__(self, accountCode):
i = 0
all_Procedures = []
dns_tns = cx_Oracle.makedsn("gbhenora06vd.corp.amvescap.net", "1525", "INVU")
db=cx_Oracle.connect("CORP-SVC-IFT", "C$Rp$vc1ftUat",dns_tns)
cursor = db.cursor()
cursor.execute("select procedure_name from all_procedures where object_name = 'PK_IVZ_IFT_EXTRACT' ")
rows = cursor.fetchall()
procedureName = ['PK_IVZ_IFT_EXTRACT.'+str(list(rows[indexRow])[0]) for indexRow in range(0,len(list(rows)))]
l_cur = cursor.var(cx_Oracle.CURSOR)
while i < len(procedureName):
if procedureName[i] == 'PK_IVZ_IFT_EXTRACT.SP_IVZ_IFT_EXTRACT_ACCOUNTS':
ret_cursor = cursor.callproc(procedureName[i],(l_cur,))
dfx = pd.DataFrame(ret_cursor[0])
all_Procedures.append(dfx)
else:
ret_cursor = cursor.callproc(procedureName[i],(l_cur,accountCode))
dfx = pd.DataFrame(ret_cursor[0])
all_Procedures.append(dfx)
i += 1
self.all_Procedures = all_Procedures
cursor.close()
db.close()
#property
def getallProcedures(self):
return self.all_Procedures
if __name__ == '__main__':
Procedures = []
all_Proc = IFTDataCore('TOUHI')
Procedures = all_Proc.getallProcedures()
print(Procedures[0])
PS: The code works fine if I do not put the logic in init and call the def logic directly in code. Please let me know the possible reason why when class initialization is done in main, the definition starts throwing error.
The solution works fine now as per the below code:
from pandas.core.frame import DataFrame
import cx_Oracle
import pandas as pd
import sys
import json
from pathlib import Path
import os
class IFTDataCore:
def __init__(self):
try:
db = cx_Oracle.connect('invest/invest#INVD.WORLD')
cursor = db.cursor()
cursor.execute("select procedure_name from all_procedures where object_name = 'PK_IVZ_IFT_EXTRACT' ")
rows = cursor.fetchall()
procedureName = ['PK_IVZ_IFT_EXTRACT.'+str(list(rows[indexRow])[0]) for indexRow in range(0,len(list(rows))-1)]
# To convert Accounts procedure to JSON format
l_cur_Account = cursor.var(cx_Oracle.CURSOR)
ret_cursor_Account = cursor.callproc(procedureName[1],(l_cur_Account,))
self.dfx_Account = pd.DataFrame(ret_cursor_Account[0])
self.dfx_Account.columns = ['fundCode', 'fundName', 'legalEntitiyIdentifier','isin']
result_Account = self.dfx_Account.to_json(orient='records')
except BaseException as e:
raise
def lambda_handler(event, context):
positional_data = IFTDataCore()
df_acct = positional_data.dfx_Account
df_acct=df_acct.fillna("")
Json=df_acct.to_json(orient='records')
lambda_response = __lambda_response__('200', Json)
return lambda_response
def __lambda_response__(status_code, response_body):
return {
'statusCode': status_code,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,GET'
},
'body': response_body
}

datetime.combine() gets my Flask app and pc blocked

I am using Flask app to get info from all daily hours from SQLAlchemy
If SQLAlchemy query.all() doesn't return all hours of the day, because they doesn't exists in the target table, I use a for loop to insert the missing hours before return with jsonfy to the route.
I have a route like this
import os
from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
import datetime as dt
#app.route("/getall")
def get_all():
try:
ttt = TruckTurnaroundTime.query.filter(TruckTurnaroundTime.hour != None).all()
for i, o in enumerate(ttt):
if i == 0:
if o.hour != dt.time(0, 0):
ttt.insert(i, TruckTurnaroundTime(dt.time(0, 0), None))
old_o = o
continue
current_hour = (dt.datetime.combine(dt.date(1, 1, 1), old_o.hour) + dt.timedelta(hours=1)).time()
if o.hour != current_hour:
ttt.insert(i, TruckTurnaroundTime(current_hour, None))
old_o = o
return jsonify([e.serialize() for e in ttt])
except Exception as e:
return(str(e))
The problem is that when I go to the route (via browser) my computer just simply blocks and never loads the route "/getall"
If I get rid of this lines:
if o.hour != current_hour:
ttt.insert(i, TruckTurnaroundTime(current_hour, None))
the problem dissapears.
I think the problem is something related with dt.datetime.combine() but I don't know.
This is my models.py:
from app import db
class TruckTurnaroundTime(db.Model):
__tablename__ = 'truck_turnaround_time'
id = db.Column(db.Integer, primary_key=True)
hour = db.Column(db.Time())
truck_turnaround_time = db.Column(db.Float)
def __init__(self, hour, truck_turnaround_time):
self.hour = hour
self.truck_turnaround_time = truck_turnaround_time
def __repr__(self):
return '<id {}>'.format(self.id)
def serialize(self):
return {
'hour': str(self.hour),
'truck_turnaround_time': self.truck_turnaround_time
}
EDIT: Python version 3.8.5

TypeError: float() argument must be a string or a number, not 'ImmutableMultiDict'

This is my flask deployment code i am trying to append the all the values from request from but i am getting this error TypeError: float() argument must be a string or a number, not 'ImmutableMultiDict'
how to append all the values from request from to deploy my model.
I am having trouble in converting string to list of dictionary.
#app.route("/")
#cross_origin()
def home():
return render_template("about.html")
#app.route("/predict", methods = ["GET", "POST"])
#cross_origin()
def predict():
if request.method == 'POST':
# Date_of_Journey
Day= request.form["DAY"]
# Month
Month=request.form["MONTH"]
# Departure time
Dept_time = request.form["DEPARTURE_TIME"]
# Arrival time
Arr_time = request.form["ARRIVAL_TIME"]
# Scheduled time
Sch_time=request.form["SCHEDULED_TIME"]
# Taxi in
taxi_in=request.form["TAXI_IN"]
# Taxi Out
taxi_out=request.form["TAXI_OUT"]
# Arrival_Delay
arr_delay=request.form["ARRIVAL_DELAY"]
# Air System Delay
air_system=request.form["AIR_SYSTEM_DELAY"]
# Airline Delay
airline_delay=request.form["AIRLINE_DELAY"]
#Aircraft Delay
aircraft_delay=request.form["LATE_AIRCRAFT_DELAY"]
# Weather Delay
weather=request.form["WEATHER_DELAY"]
**result=request.form
pkl_file = open('cat', 'rb')
index_dict = pickle.load(pkl_file)
new_vector = np.zeros(len(index_dict))
try:
new_vector[index_dict['ORIGIN_AIRPORT'+str(result['origin'])]] = 1
except:
pass
try:
new_vector[index_dict['DESTINATION_AIRPORT'+str(result['destination'])]] = 1
except:
pass
try:
new_vector[index_dict['AIRLINE'+str(result['airline'])]] = 1
except:
pass**
prediction=Rf.predict([[
Day,
Month,
Dept_time,
Arr_time,
Sch_time, taxi_in,taxi_out,arr_delay,air_system,airline_delay,aircraft_delay,weather,
result
]])
output=round(prediction[0])
return render_template('about.html',prediction_text=" Flight delayed by {} mins".format(output))
return render_template('about.html')
if __name__ == "__main__":
app.run()

Is it possible to have Celery run an infinite loop in the background? (flask)

I have the following celery task:
#celery.task
def ScrapeWhileTrue():
current_titles = scrape_title()
current_urls = scrape_url()
while(True):
time.sleep(10)
print("completing a test")
current_titles2 = scrape_title()
current_urls2 = scrape_url()
if current_titles != current_titles2:
print("New listings!")
new_titles = set(current_titles2) - set(current_titles)
new_urls = set(current_urls2) - set(current_urls)
# send_mail(new_titles, new_urls)
current_titles = current_titles2
current_urls = current_urls2
Mt HTML contains two buttons, one which sends the data from the form to a different function. The second button I would like to be toggle-able. While its toggled, I would like it to run the above Celery task.
#app.route('/', methods=['GET', 'POST'])
def index():
if request.form['submit'] == 'Send':
#Set info
global url
url = CraiglistScraper(location, postal, max_price, radius, query, carorpart)
flash('Info set')
else:
flash('Scraping')
ScrapeWhileTrue()
return redirect(url_for('index'))
Is it possible to have something like this happen? Or would I need to run it as a Daemon (I have no idea how)?
Thanks!

Categories

Resources