所以我现在已经坚持这个问题一段时间了。对于一个文件我有它正在工作,它允许我使用烧瓶框架。使用此代码。
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)
但是使用此代码会抛出错误。没有名为&#39; flask&#39;
的模块#!/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)
我觉得这个问题将与我使用的python / flask / pip版本有关。任何想法都谢谢你。
答案 0 :(得分:2)
您的Python版本是2.X。
查看this question及其答案。
您最好的选择是使用virtualenv,因为它使处理包版本变得非常简单。如果要将Python 3用于此应用程序,accepted answer包含正确的命令提示符命令:
virtualenv -p C:\Python34\python.exe py3env
py3env\Scripts\activate
pip install package-name
答案 1 :(得分:1)