I get the following error for encoding when I activate DEBUG mode:
set FLASK_DEBUG=1
For some reason, the debug mode does not get activated by app.debug=True. Here is the error:
Non-UTF-8 code starting with '\x90' in file
C:\Users\mypc\Anaconda3\envs\fenv\Scrip
ts\flask.exe on line 1, but no encoding declared; see
http://python.org/dev/peps/pep-0263/ for de
tails
I tried the solution in the this link but it didn't help!
Working with utf-8 encoding in Python source
Then I tried the following command:
python -m flask run
And I got the following error:
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
This is my code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, url_for, request, render_template, jsonify
import requests, json
from urllib.request import quote
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] =
'postgresql://postgres:password#localhost/flask'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
#app.route('/')
def Index():
return render_template('add_user.html')
#app.route('/postuser', methods=['POST'])
def post_user():
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
Related
from crypt import methods
from distutils.log import debug
from flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///reg.db'
db = SQLAlchemy(app)
class Todo(db.Model):
name = db.Column(db.String(200), nullable=False)
Bdate = db.Column(db.Integer(), nullable=False)
Gender = db.Column(db.String(6), nullable = False)
Class = db.Column(db.String(9), nullable = False)
Registration = db.Column(db.Integer(), primary_key = True)
date_created = db.Column(db.DateTime, default= datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
SQLALCHEMY_TRACK_MODIFICATIONS = False #to supress warning in terminal
#app.route('/', methods=['POST','GET'])
def index():
if request.method == "POST":
pass
task_content = request.form['card-body']
new_task = Todo(content = task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect('/')
except:
return "Their Was An Error"
else:
task = Todo.query.order_by(Todo.date_created).all()
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Here is my code i dont know how to modify the code to get it run on my Windows. Its my first day of learning flask Please help me out
from crypt import methods
line 9, in <module>
raise ImportError("The crypt module is not supported on Windows")
ImportError: The crypt module is not supported on Windows
this is the error i m getting. Its mostly becasue of POST AND GET in method I guess and i m unable to solve this. I m working on db connection to form in html with the help of Youtube and the guy isusing UNIX so doesnt have any problem but my windows suks here.
you had automatically made this import: from crypt import methods when you were typing this line of code #app.route('/', method... . but this crypt is a Python module used to check Unix passwords and you are using windows. anyway it has nothing to do with flask just delete this line from crypt import methods
I have a Flask web application that has an sqlite database called data.db which contains the data of user/admin. Whenever I try to query the data on my python file routes.py it returns an ImportError message. However, when I query the data from my conda terminal it works properly, I got the desired result. Is there's any solution for this? I wonder what I did wrong
this is the init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
app = Flask(__name__)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'admin_login'
app.config['SECRET_KEY'] = 'my secret key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
from yves_letters import routes
this is the models.py
from yves_letters import db
from flask_login import UserMixin
class Admin(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True)
display_name = db.Column(db.String(20))
password = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f'id: {self.id}, username: {self.username}, display_name: {self.display_name}, password: {self.password}'
this is the routes.py
from yves_letters.models import Data, Admin
#app.route('/')
def home():
admin = Admin.query.all()
return render_template('home.html')
this is the error I'm getting while running the code
ImportError
ImportError: DLL load failed: The specified module could not be found.
Traceback (most recent call last)
File "C:\Users\USER\anaconda3\envs\webapp_env\lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
Open an interactive python shell in this framereturn self.registry[key]
On the other hand, when I do the query from my conda terminal it's working well.
admin = Admin.query.all()
admin
[id: 1, username: admin, display_name: Mac Yves]
Is there's something I missed?
Help!
I'm really new to flask and I've been muddling along with all the tutorials I could find but I've run into a problem I can't figure out.
Here's my error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: User
[SQL: SELECT "User"."userId" AS "User_userId", "User".email AS "User_email", "User".password AS "User_password", "User".username AS "User_username", "User".lastlogin AS "User_lastlogin", "User".isauthenticated AS "User_isauthenticated"
FROM "User"
WHERE "User".email = ?
LIMIT ? OFFSET ?]
[parameters: ('test#example.com', 1, 0)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
So I'm working on the signup form and I've solved all the other bugs. But here what I can make out from this error is that my database or table isn't being created.
Here's my code:
init.py:
import os
from flask import Flask, render_template, redirect, session
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import import_string
from complete.app import redirect_url
db = SQLAlchemy()
login_manager = LoginManager()
def create_app():
"""Create Flask application."""
app = Flask(__name__, instance_relative_config=False)
#app.context_processor
def inject_global_vars():
return dict(appname="Ebay Listing Viewer")
app.config.from_pyfile('configfile.py')
db.init_app(app)
login_manager.init_app(app)
with app.app_context():
from .userauth.auth import auth_bp
app.register_blueprint(auth_bp)
db.create_all()
from .models import User
#login_manager.user_loader
def load_user(user_id):
return User.get(user)
return app
models.py:
"""Data Models"""
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
__tablename__ = 'User'
userid = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(200))
username = db.Column(db.String(1000))
lastlogin = db.Column(db.DateTime)
isauthenticated = db.Column(db.Boolean, default=False)
def is_active(self):
return True
def get_id(self):
return chr(self.userId)
def is_authenticated(self):
return self.isauthenticated
def is_anonymous(self):
return False
def __repr__(self):
return '<User> {}'.format(self.username)
def set_password(self, password):
self.password = generate_password_hash(
password,
method='sha256'
)
def check_password(self, password):
return check_password_hash(self.password, password)
config.py:
class Config(object):
"""Base config."""
SECRET_KEY = environ.get('SECRET_KEY')
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
class DevelopmentConfig(Config):
FLASK_ENV = 'development'
SQLALCHEMY_DATABASE_URI = environ.get('DEV_DATABASE_URI')
.env:
#among other things...
DEV_DATABASE_URI=sqlite:///db.sqlite
There is a file called db.sqlite in my root folder (ie the same directory as init.py) but I'm not sure it's got anything in it. When I try to open it, it shows The file is not displayed in the editor because it is either binary or uses an unsupported text encoding. (I'm using VSCode).
I'm not quite sure how the database uri works - I've had a lot of looks around Google and everyone seems to think it's completely obvious. Is it the file path to my database file? Do I create the database file or is it automatically created?
I'm thinking the problem is likely to be that the database uri is wrong, but I dunno, I haven't got enough experience so maybe it's something completely different.
Thank you for taking the time to read and help!
I am following this tutorial to build a JWT based authentication system.
app.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'd0cad49580952003e6ae01499c7bb190a4b4f9a5babd866f47064707f7b78506'
api = Api(app)
db = SQLAlchemy(app)
#app.before_first_request
def create_tables():
db.create_all()
import resources, models
api.add_resource(resources.UserRegistration, '/registration')
if __name__ == '__main__':
app.run()
models.py:
from app import db
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(150), nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
def __init__(self, name, password, email):
self.name = name
self.password = password
self.email = email
#classmethod
def find_by_username(cls, username):
return cls.query.filter_by(username=username).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
resources.py:
from flask_restful import Resource, reqparse
from models import UserModel
class UserRegistration(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('name', help='This field cannot be blank', required=True)
parser.add_argument('email', help='This field cannot be blank', required=True)
parser.add_argument('password', help='This field cannot be blank', required=True)
data = parser.parse_args()
if UserModel.find_by_username(data['name']):
return {'message': 'User {} already exists'.format(data['name'])}
new_user = UserModel(
name=data['name'],
password=data['password'],
email=data['email']
)
try:
new_user.save_to_db()
return {
'status': 'User {} was created'.format(data['username'])}
except:
return {'message': 'Something went wrong'}, 500
When I run app.py, I get the following error:
Traceback (most recent call last):
File "G:\python\PycharmProjects\vumonic\app.py", line 19, in <module>
import resources, models
File "G:\python\PycharmProjects\vumonic\resources.py", line 2, in <module>
from models import UserModel
File "G:\python\PycharmProjects\vumonic\models.py", line 1, in <module>
from app import db
File "G:\python\PycharmProjects\vumonic\app.py", line 21, in <module>
api.add_resource(resources.UserRegistration, '/registration')
AttributeError: module 'resources' has no attribute 'UserRegistration'
This error dissapears when I remove from models import UserModel from resources.py.
I cannot figure out the reason for the error.
I am using Flask==1.1.2, Flask-SQLAlchemy==2.4.4 and Flask-RESTful==0.3.8
This is the first time Iam developing an API so any help would be appreciated.
you are facing circular import issue.
When Python imports a module, it checks the module registry to see if the module was already imported. If the module was already registered, Python uses that existing object from cache. The module registry is a table of modules that have been initialized and indexed by module name. This table can be accessed through sys.modules.
If it was not registered, Python finds the module, initializes it if necessary, and executes it in the new module's namespace.
to know more about circular import you can read the article:
https://stackabuse.com/python-circular-imports/
https://www.stefaanlippens.net/circular-imports-type-hints-python.html
this tutorial of Miguel Grinberg is a life savior
https://www.youtube.com/watch?v=NH-8oLHUyDc&t=3205s
I'm trying to integrate PostgreSQL and SQLAlchemy but SQLAlchemy.create_all() is not creating any tables from my models.
My code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass#localhost/flask_app'
db = SQLAlchemy(app)
db.create_all()
db.session.commit()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
admin = User('admin', 'admin#example.com')
guest = User('guest', 'guest#example.com')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
But I get this error: sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "user" does not exist
How can I fix this?
You should put your model class before create_all() call, like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass#localhost/flask_app'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
with app.app_context():
db.create_all()
db.session.add(User('admin', 'admin#example.com'))
db.session.add(User('guest', 'guest#example.com'))
db.session.commit()
users = User.query.all()
print(users)
If your models are declared in a separate module, import them before calling create_all().
Say, the User model is in a file called models.py,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass#localhost/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
with app.app_context():
db.create_all()
db.session.add(User('admin', 'admin#example.com'))
db.session.add(User('guest', 'guest#example.com'))
db.session.commit()
users = User.query.all()
print(users)
Important note: It is important that you import your models after initializing the db object since, in your models.py you also need to import the db object from this module.
If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared.
So, if the filesystem is like this:
Root
--app.py <-- file from which app will be run
--models
----user.py <-- file with "User" model
----order.py <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration
Be careful about calling the "create_all" function from app.py.
This concept is explained better by the answer to this thread posted by #SuperShoot
This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
I also have a separate cli command that also does the create_all:
# tasks/db.py
from lib.db import get_db
#current_app.cli.command('init-db')
def init_db():
db = get_db()
db.create_all()
I also am using a application factory.
When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).
The fix that I came around to was to make sure that the db was a single global reference:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
db = None
def get_db():
global db
if not db:
db = SQLAlchemy(current_app)
return db
I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.