configure database in flask - python

i am trying to configure database in flask but whenever i run the app than it give an error :- ImportError: No module named flask_peewee.db
from flask import Flask
from flask_peewee.db import Database
app = Flask(__name__)
app.config.from_object(__name__)
DATABASE = {
'name': 'flasktesting.db',
'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = 'ssshhhh'
app = Flask(__name__)
app.config.from_object(__name__)
# instantiate the db wrapper
db = Database(app)
#app.route('/')
def Hello_World():
return ' Are You Ready !!!!!!!!'
if __name__ == '__main__':
app.run()

Do you actually have flask_peewee installed? I ran your code and it worked perfectly with
flask_peewee being installed.
Try to run pip install flask_peewee.

Related

Trouble running Flask alongside uWSGI/Nginx

I'm currently facing issues running my Flask app, and I suspect it's related to a recent restructure of my main app files. I'm struggling to identify the source of the problem and would greatly appreciate any assistance.
When I try to run the app using the flask run command, the website is only accessible on the default port 5000. Attempting to access the website at http://127.0.0.1:5000/ results in the error message "This site can't be reached 127.0.0.1 refused to connect."
I've tried changing the port number in the run.py file to a custom value, but despite updating the code, the logs still indicate that the app is using port 5000. Additionally, I've verified that port 5000 isn't being used by any other process.
I have tried disabling the firewall and verifying that there are no other network issues, but the problem still persists.
I'm uncertain whether the issue is with my code or the server configuration, but I suspect it may be related to the recent restructuring of the main app files.
Notably, uWSGI has no problem running on the domain or IP address.
Any insights or solutions to this issue would be greatly appreciated. Thank you for your help.
Below, I have provided the relevant code for context:
Evidenca-2.0/wsgi.ini
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = wsgi.sock
chmod-socket = 660
vacuum = true
die-on-term = true```
Evidenca-2.0/wsgi.py
from run import app
if __name__ == '__main__':
app.run()
Evidenca-2.0/run.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_minify import Minify
import os
import logging
from apps.config import config_dict
from apps import create_app, db
# Configure the app
app_config_mode = os.getenv('FLASK_ENV', 'development')
try:
app_config = config_dict[app_config_mode.capitalize()]
except KeyError:
logging.warning(f'Invalid config mode: {app_config_mode}. Defaulting to development mode.')
app_config = config_dict['Development']
app = create_app(app_config)
# Initialize extensions
db = SQLAlchemy()
migrate = Migrate(app, db)
minify = Minify(app=app, html=True, js=False, cssless=False)
# Configure logging
log_file_name = 'app.log'
if app_config.DEBUG:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logging.basicConfig(filename=log_file_name, level=log_level)
if app_config.DEBUG:
logging.debug(f'DEBUG = {app_config.DEBUG}')
logging.debug(f'FLASK_ENV = {os.getenv("FLASK_ENV")}')
logging.debug(f'Page Compression = {"FALSE" if app_config.DEBUG else "TRUE"}')
logging.debug(f'DBMS = {app_config.SQLALCHEMY_DATABASE_URI}')
logging.debug(f'ASSETS_ROOT = {app_config.ASSETS_ROOT}')
logging.debug(f'UPLOAD_FOLDER = {app_config.UPLOAD_FOLDER}')
# Start the app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, threaded=True)
Evidenca-2.0/apps/config.py:
import os
from sqlalchemy import create_engine
from flask import Flask
class Config:
basedir = os.path.abspath(os.path.dirname(__file__))
# Set up the App SECRET_KEY
SECRET_KEY = os.getenv('SECRET_KEY', 'S#perS3crEt_007')
# Set up the database configuration
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI', 'mysql+pymysql://aviat:admin#localhost/Evidenca')
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Flask-User settings
USER_APP_NAME = "Flask-User QuickStart App" # Shown in and email templates and page footers
USER_ENABLE_EMAIL = False # Disable email authentication
USER_ENABLE_USERNAME = True # Enable username authentication
USER_REQUIRE_RETYPE_PASSWORD = False # Simplify register form
# Assets Management
ASSETS_ROOT = os.getenv('ASSETS_ROOT', '/static/assets')
# File Upload
UPLOAD_FOLDER = os.getenv('UPLOAD_FOLDER', '/uploads')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Set up logging
LOG_FILE_NAME = os.getenv('LOG_FILE_NAME', 'app.log')
LOG_LEVEL = os.getenv('LOG_LEVEL', 'DEBUG')
# Set up the MariaDB database engine
ENGINE = create_engine(SQLALCHEMY_DATABASE_URI, echo=True)
# Set up the app configuration
DEBUG = os.getenv('DEBUG', False)
SESSION_COOKIE_HTTPONLY = True
REMEMBER_COOKIE_HTTPONLY = True
REMEMBER_COOKIE_DURATION = 3600
if DEBUG:
print('DEBUG = ' + str(DEBUG))
print('FLASK_ENV = ' + os.getenv('FLASK_ENV'))
print('Page Compression = FALSE')
print('DBMS = ' + SQLALCHEMY_DATABASE_URI)
print('ASSETS_ROOT = ' + ASSETS_ROOT)
print('UPLOAD_FOLDER = ' + UPLOAD_FOLDER)
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = False
class DebugConfig(Config):
DEBUG = True
# Load all possible configurations
config_dict = {
'Production': ProductionConfig,
'Development': DevelopmentConfig,
'Debug': DebugConfig
}
Evidenca-2.0/apps/_init_.py:
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2023 - Aviat Networks
This module sets up the main application and initializes its components. It also
registers the necessary extensions and blueprints for the application.
"""
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from importlib import import_module
# Initialize flask app, SQLAlchemy database, and LoginManager
app = Flask(__name__)
db = SQLAlchemy()
login_manager = LoginManager()
def register_extensions(app):
"""
Register the necessary extensions for the application.
"""
db.init_app(app)
login_manager.init_app(app)
def register_blueprints(app):
"""
Register the blueprints for the application.
"""
for module_name in ('authentication', 'inventory'):
module = import_module('apps.{}.routes'.format(module_name))
if module_name == 'authentication':
app.register_blueprint(module.auth_bp, url_prefix='/auth')
if module_name == 'inventory':
app.register_blueprint(module.inventory_blueprint)
def configure_database(app):
"""
Configure the database for the application.
"""
# Initialize the database before the first request
#app.before_first_request
def initialize_database():
db.create_all()
# Remove database session after each request
#app.teardown_request
def shutdown_session(exception=None):
db.session.remove()
def create_app(config):
"""
Create and configure the Flask application.
:param config: The configuration object for the application.
:return: The Flask application instance.
"""
app = Flask(__name__)
app.config.from_object(config)
register_extensions(app)
register_blueprints(app)
configure_database(app)
return app
The odd thing is that it works, if I set it up like this: flask run -h 192.168.X.X How come it doesn't work on localhost?

Why flask app run but browser is not loading the page?

I was developing a web application and it was woking fine, then I closed the project and re-opened it after a few hours, the project ran without error, but when I go to localhost:5000 it doesn't even load. I tried the same project in another laptop and it works perfectly.
I also tried a simple project in the problematic one like this. The program run, but the browser won't load the page, also here if I use my second laptop it works perfectly. What I should do to fix? Literally like 2 hours ago was working fine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
My application code is:
from flask import Flask, render_template
from flask_login import current_user, LoginManager
from DaisPCTO.db import get_user_by_id
from flask_bootstrap import Bootstrap
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = "qwnfdopqwebnpqepfm"
Bootstrap(app)
login_manager = LoginManager()
login_manager.login_view = "auth_blueprint.login"
login_manager.init_app(app)
#app.route("/")
def home():
print("hello")
return render_template("page.html", user=current_user, roleProf = True if current_user.is_authenticated and current_user.hasRole("Professor") else False)
#login_manager.user_loader
def load_user(UserID):
return get_user_by_id(UserID)
from DaisPCTO.auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from DaisPCTO.courses import courses as courses_blueprint
app.register_blueprint(courses_blueprint, url_prefix="/courses")
return app
i'm not putting all the blueprint, this is only the init.py file
In you application you don't run your app you just create a function
if __name__ == '__main__':
app = create_app()
app.run()
If you add this to your code you should be abble to see it in http://localhost:5000

How to solve Import "flask_cors" could not be resolved from source

I'm doing a web based project using flutter and flask. when I tried to use API to communicate between flutter and flask(note : I'm new to dealing with API's).
I got XML Http Request error, I tried all the solutions available but still no use and later found that installing flask-CORS module in flask can help resolve the issue. while importing flask-CORS module I faced with the above error.
Flask-CORS path and error
Flutter API code
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
CORS(app)
app.config['ENV'] = "development"
#app.route('/auth',methods=["POST"])
#cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em+"\t"+pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)
https://flask-cors.readthedocs.io/en/latest/
Allow access to all apis that starts with /api from all origins.
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
or if you are testing from local try
cors = CORS(app, resources={r"/api/*": {"origins": ["http://localhost:5000/*"]}})
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['ENV'] = "development"
#app.route('/auth',methods=["POST"])
#cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em+"\t"+pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)

FlaskApp has no attribute 'config'

all. I writing project using Flask, SQLAlchemy, and connexion. Before connexion was implemented, all works success (p.s. when app created as app = Flask(__name__). After implementing connexion raises an exception:
'SQLALCHEMY_DATABASE_URI' not in app.config and AttributeError: 'FlaskApp' object has no attribute 'config'. So where is a mistake? Help, please.
run.py:
from app import create_app
app = create_app('development')
if __name__ == '__main__':
app.run()
app:
...
from settings import app_config
db = SQLAlchemy()
def create_app(config_name):
# app = Flask(__name__)
app = connexion.App(__name__)
app.add_api('swagger.yml')
application = app.app
application.config.from_object(app_config[config_name])
application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
return app
settings.py
class BaseConfig(object):
DEBUG = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET', 'default_secret_key')
DEFAULT_URI = 'postgresql://shooter:shooter#localhost/shooterstats'
SQLALCHEMY_DATABASE_URI = DEFAULT_URI
class DevelopmentConfig(BaseConfig):
DEBUG = True
There was a mistake here db.init_app(app). I changed it to db.init_app(application) and it is working success now.
Here is one way you can set up your Flask application with Connexion.
import connexion
# This creates the connexion application instance.
connexion_app = connexion.App(__name__)
# This gets the underlying Flask app instance.
flask_app = connexion_app.app # Flask(__name__)
🤠

ResponseError: operation not permitted

import config
from flask import Flask
from flask_redis import Redis
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
redis_store = Redis(app)
app.debug = config.DEBUG
app.redis_url = config.REDIS_URL
#app.route('/')
def index():
return redis_store.ping()
app.wsgi_app = ProxyFix(app.wsgi_app)
if __name__ == '__main__':
app.run()
config.py
DEBUG = True
REDIS_URL = "redis://:123#localhost:6379/0"
/etc/redis/redis.conf
...
requirepass 123
ERROR:
raise response
ResponseError: operation not permitted
Seems like the AUTH command is not executed, or something similar. Any idea about the possible problem?
According to its README, Flask-Redis looks for a key called REDIS_URL as part of the Flask config.
Configuration
Your configuration should be declared within your Flask config. You can declare
via a Redis URL containing the database
REDIS_URL = "redis://:password#localhost:6379/0"
Without setting that redis_store will just use the default settings, which won't include your password.
app = Flask(__name__)
app.config['REDIS_URL'] = config.REDIS_URL
redis_store = Redis(app)

Categories