简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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