自从我升级到 Flask 2.3 后,当我尝试在 VSC 中从 powershell 运行代码时,出现错误。有谁知道如何修复错误?

问题描述 投票:0回答:1

这是我运行 conda update conda 并获得 Flask 版本 2.3 之前的工作。

>>$env:FLASK_APP="wsgi"
>>$env:FLASK_ENV="development" 
>>flask run

这是我升级到 Flask 2.3 后尝试的方法,我无法使用 $env:FLASK_ENV="development" 因为我收到一条错误消息说 use FLASK_DEBUG=1

>>$env:FLASK_APP="wsgi"
>>$env:FLASK_DEBUG=1
>>flask run

这是我运行上述命令后的错误https://pastebin.com/NNEhi5GW

这是我当前环境中的 conda 列表https://pastebin.com/rm7qv0Aq

这是相关代码

应用程序/init.py

# __init__.py in not in users folder  
from flask import Flask
from flask_ckeditor import CKEditor
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_redmail import RedMail
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

# Setup CSRF protection. This allows html forms to work and be secure
csrf = CSRFProtect()
# make mail work
email = RedMail()
ckeditor = CKEditor() 
app = Flask(__name__)
# Make @login_required work
login_manager = LoginManager(app)
# You get a custom login message when @login_required appears in the code.
login_manager.login_message_category = 'Login is required'
# Should I use auth.login ? What is this?
login_manager.login_view = 'login' 
# setup databases
db = SQLAlchemy()
#for flask migrate
migrate = Migrate(app, db)

from app.models import User
# Use User.query.get instead of User.get because of sqlalchemy ?
# This function logs you in and since there is no way of storing it in the database I need the function.
# Add @app because of the way the app is structured.
@app.login_manager.user_loader
def load_user(id):
    return User.query.get(id) 
 
from app.config import DevelopmentConfig, PytestConfig,Config
def get_multiple_configs():    
    '''
    Allows multiple configs.
    For example if I type in the terminal development,
    I will get that config. 
    '''
 
    if app.config['DEBUG'] == 'True':
        env_name = DevelopmentConfig(Config)
        return env_name  
    elif app.config['DEBUG'] == 'False':
        env_name = PytestConfig(Config)
        return env_name
         
def create_app(config_env=get_multiple_configs): 
    # The function name is from the config file which is "Class config:".
    app.config.from_object(config_env)
    migrate.init_app(app, db)
    db.init_app(app)
    login_manager.init_app(app)
    email.init_app(app)
    csrf.init_app(app) 
    # blocks this from pytest. Because I get a weird error when it runs in pytest
    if app.config['WTF_CSRF_ENABLED'] == True:
        ckeditor.init_app(app)
   
    from app.auth.routes import auth
    from app.mail.routes import mail
    from app.payment.routes import payment
    from app.postinfo.routes import postinfo

    app.register_blueprint(auth) 
    app.register_blueprint(postinfo)
    app.register_blueprint(mail)
    app.register_blueprint(payment)

    return app 

应用程序/config.py

import os
import stripe
# This gives the path the current folder is in. This is an absolute import. 
# example below
# C:\Users\username\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app
base_directory = os.path.abspath(os.path.dirname(__file__))

from datetime import timedelta

# what does sqlite/// do ?
# what is object ?
class Config(object): 
    # Setup CSRF secret key
    # change to environment variable todo!
    SECRET_KEY = 'temp_secret_key'
    # this is the test key for stripe 
    stripe.api_key = os.environ['STRIPE_SECRET_KEY']
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    # DATABASE_URI = sqlite:///app.db, this is the the default path, or 
    # " 'sqlite:///' " + "os.path.join(base_directory, 'app.db')" = sqlite:///C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\app.db
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') or \
    'sqlite:///' + os.path.join(base_directory, 'app.db')   # correct
    ''' Database For pytest'''
    # DATABASE_URI = sqlite:///test_app.db", this the default path, or 
    # " 'sqlite:///' " + "os.path.join(base_directory, 'test_app.db')" = sqlite:///C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\test_app.db
    PYTEST_DATABASE_URI = os.environ.get('TEST_DATABASE_URI') or \
    'sqlite:///' + os.path.join(base_directory, 'test_app.db')
    # for 2+ databases to make the second db work
    SQLALCHEMY_BINDS = { "testing_app_db": PYTEST_DATABASE_URI }
    # setting up Outlook email for flask-redmail
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_PORT  = 587
    # The max file size is now 16 megabytes.
    MAX_CONTENT_LENGTH = 16 * 1000 * 1000
    # logs you in for 6 min after closing the browser 
    REMEMBER_COOKIE_DURATION = timedelta(seconds=360)

from pathlib import Path

class DevelopmentConfig(Config):    
    # makes the debugger work
    DEBUG = True
    #  for pytest?
    TESTING = True    
    # need this to prevent error in redmail. 
    SECURITY_EMAIL_SENDER = "[email protected]"
    # This will be the same value as ['DEBUG'] = ... 
    Mail_DEBUG = True  
    # This is the default email that you get when you send an email?
    MAIL_DEFAULT_SENDER = None  
    # You can only send x amount of emails at one time. Can also be set to None.
    MAIL_MAX_EMAILS = 5  
    # same value ['TESTING'] =. If you are testing your app if you don't want to send emails make it True?
    # ['MAIL_SUPRESS_SEND'] = False 
    # converts the file name to ascii. ascii characters are english characters. (Why use this?)
    MAIL_ASCII_ATTACHMENTS = False 
    # Used to save to the uploaded folder 
    # UPLOAD_FOLDER = r"C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2\app\static\profilepictures"
    #UPLOAD_FOLDER = os.path.abspath(base_directory + r"\app\static\profilepictures")
    UPLOAD_FOLDER = Path.cwd().joinpath("app", "static", "profilepictures")
    # max a file can be is 1 megabyte is that big enough? Todo add warning
    MAX_CONTENT_LENGTH = 1024 * 1024
    CKEDITOR_PKG_TYPE = 'standard'
    
    from redmail import gmail
    # setting up gmail for flask-redmail
    gmail.username = os.environ['EMAIL_USERNAME']
    gmail.password = os.environ['EMAIL_PASSWORD']
    
    # setting up the Outlook email for flask-redmail
    # from redmail import outlook
    # outlook.username = os.environ['EMAIL_USERNAME']
    # outlook.password  = os.environ['EMAIL_PASSWORD']
    # EMAIL_HOST = 'smtp.office365.com'
    # EMAIL_PORT = '587'    
    
    '''
    # depends on email provider
    MAIL_PORT =  None 
    # used for security purposes depend on email provider
    MAIL_USE_TLT = False
    MAIL_USE_SSL = False 
    ''' 
    '''
    # username of the linked mail account  
    MAIL_USERNAME = None
    # password of the linked mail account
    MAIL_PASSWORD = None
    '''
    # make secret key work in wtf forms
    WTF_CSRF_ENABLED = True
 

class PytestConfig(Config): 
    DEBUG = False
    EMAIL_HOST = 'localhost'
    EMAIL_PORT = '0' 
    Mail_DEBUG = True  
    # for pytest?
    TESTING = True     
    # This is the same value ['TESTING'] =...
    # If you are testing your app and you don't want to send emails make the value True?
    MAIL_SUPRESS_SEND = True  
    # When this is False wtf_forms is disabled. This makes 'POST' request work for pytest routes.
    WTF_CSRF_ENABLED = False
    SQLALCHEMY_TRACK_MODIFICATIONS = True 
    SERVER_NAME = 'localhost'

我还有一个 app/wsgi.py 文件,我在其中调用 create_app,我需要它来与 pytest 的配置一起使用。如何让代码运行?

我设法找到解决方案

我确实有一个解决方案,通过点击下面的链接并将

PytestConfig
中的代码移动到应用程序固定装置中。

https://flask.palletsprojects.com/en/3.0.x/testing/

现在我只有一个配置。我很好奇是否可以保留

DevelopmentConfig
PytestConfig

python flask pytest flask-sqlalchemy
1个回答
0
投票

解决方案是去掉下面的代码

def get_multiple_configs():    
    '''
    Allows multiple configs.
    For example if I type in the terminal development,
    I will get that config. 
    '''
 
    if app.config['DEBUG'] == 'True':
        env_name = DevelopmentConfig(Config)
        return env_name  
    elif app.config['DEBUG'] == 'False':
        env_name = PytestConfig(Config)
        return env_name

并将其替换为

def create_app(): 
    app = Flask(__name__) 
    current_config = os.environ['FLASK_ENV']
    if current_config == 'dev':
        app.config.from_object(DevelopmentConfig)
    elif current_config == 'test':
        app.config.from_object(PytestConfig)
    migrate.init_app(app, db)
    db.init_app(app)
    login_manager.init_app(app)
    email.init_app(app)
    csrf.init_app(app) 
    # blocks this from pytest. Because I get a weird error when it runs in pytest
    if app.config['WTF_CSRF_ENABLED'] == True:
        ckeditor.init_app(app)
   
    from app.auth.routes import auth
    from app.mail.routes import mail
    from app.payment.routes import payment
    from app.postinfo.routes import postinfo

    app.register_blueprint(auth) 
    app.register_blueprint(postinfo)
    app.register_blueprint(mail)
    app.register_blueprint(payment)

    return app 

然后在 powershell 例如 vsc 中我会运行

$env:FLASK_DEBUG='真'
$env:FLASK_ENV='dev'

flask --app 应用程序运行

© www.soinside.com 2019 - 2024. All rights reserved.