简体   繁体   English

Python:没有名为“ flask”的模块

[英]Python : No module named 'flask'

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. 对于一个文件,它正在运行,并且允许我使用flask框架。 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' 没有名为“ 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. 我觉得问题将与我使用的python / flask / pip版本有关。 Any ideas thank you. 任何想法谢谢你。

Your Python version is 2.X. 您的Python版本是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. 最好的选择是使用virtualenv,因为它使处理软件包版本非常简单。 The accepted answer includes the proper command prompt commands if you want to use Python 3 for this app: 如果您想为此应用程序使用Python 3,则可接受的答案包括正确的命令提示符命令:

virtualenv -p C:\Python34\python.exe py3env
py3env\Scripts\activate
pip install package-name

I would recommend using Anaconda . 我建议使用Anaconda Download, install, then run: 下载,安装然后运行:

conda install flask

And you're done. 这样就完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM