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
Related
I've looked at the other posts with this same title, but they did not fix my problem. The error message in the above title is what I am getting.
I've made a simple database and constructor for the database. Just to test, I'm trying to add the word "hello" to the column "words" in the class User. But I keep getting this error. I've already tried putting autoincrement in the class column, but I ended it up getting another error. What is going wrong? Please see the code below. Python and Flask.
from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'user'
words = db.Column(db.String(200), primary_key=True)
def __init__(self, thewords):
self.thewords = thewords
db.create_all()
db.session.commit()
texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()
results = User.query.all()
print(results)
#app.route('/', methods = ['POST', 'GET'])
def hello():
return render_template('Textarea.html')
app.run(debug=True)
For anyone who visits this page in the future, I've found what was wrong. I did not reference "words" as "self.words". My code now works and I am relieved to finally continue coding so that some other bug can confound me later down the road. Please see below. You can see the difference in code in the User class. I used query.all() to prove that data has made it into the database.
from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
words = db.Column(db.String(200), primary_key=True, nullable=False)
def __init__(self, thewords):
self.words = thewords
db.create_all()
db.session.commit()
texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()
print(User.query.all())
#app.route('/', methods = ['POST', 'GET'])
def hello():
return render_template('Textarea.html')
app.run(debug=True)
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 am doing a flask tutorial from youtube. But however i always get this error. I even copied his code and tried on my pc, but it still raise that error.
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return "<Task %r>" % self.id
#app.route("/", methods=["POST", "GET"])
def index():
if request.method == "POST":
task_content = request.form["content"]
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect("/")
except:
return "There was an issue adding your task"
else:
tasks = Todo.query.order_by(Todo.date_created).all()
return render_template("index.html", tasks=tasks)
# return "hello"
if __name__ == "__main__":
app.run(debug=True)
And this is the error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: todo
[SQL: SELECT todo.id AS todo_id, todo.content AS todo_content, todo.date_created AS todo_date_created
FROM todo ORDER BY todo.date_created]
You must create db with tables before trying to call it. Answer in the error text.
Try to read documentation There is lot of information for you. Check method: create_all and second code example from documentation:
>>> from yourapplication import db
>>> db.create_all()
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()