I’m learning flask web microframework and after initialization of my database I run flask db init
I run flask db migrate
, to migrate my models classes to the database and i got an error. I work on Windows 10, the database is MySQL, and extensions install are flask-migrate
, flask-sqlalchemy
, flask-login
.
(env) λ flask db migrate
Traceback (most recent call last):
File "c:python36Librunpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:python36Librunpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:UsersakaDevdream-teamenvScriptsflask.exe__main__.py", line 9, in <module>
File "c:usersakadevdream-teamenvlibsite-packagesflaskcli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "c:usersakadevdream-teamenvlibsite-packagesflaskcli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 697, in main
rv = self.invoke(ctx)
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagesclickdecorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagesflaskcli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagesclickcore.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagesflask_migratecli.py", line 90, in migrate
rev_id, x_arg)
File "c:usersakadevdream-teamenvlibsite-packagesflask_migrate__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "c:usersakadevdream-teamenvlibsite-packagesalembiccommand.py", line 176, in revision
script_directory.run_env()
File "c:usersakadevdream-teamenvlibsite-packagesalembicscriptbase.py", line 427, in run_env
util.load_python_file(self.dir, 'env.py')
File "c:usersakadevdream-teamenvlibsite-packagesalembicutilpyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "c:usersakadevdream-teamenvlibsite-packagesalembicutilcompat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrationsenv.py", line 87, in <module>
run_migrations_online()
File "migrationsenv.py", line 70, in run_migrations_online
poolclass=pool.NullPool)
File "c:usersakadevdream-teamenvlibsite-packagessqlalchemyengine__init__.py", line 465, in engine_from_config
return create_engine(url, **options)
File "c:usersakadevdream-teamenvlibsite-packagessqlalchemyengine__init__.py", line 424, in create_engine
return strategy.create(*args, **kwargs)
File "c:usersakadevdream-teamenvlibsite-packagessqlalchemyenginestrategies.py", line 50, in create
u = url.make_url(name_or_url)
File "c:usersakadevdream-teamenvlibsite-packagessqlalchemyengineurl.py", line 211, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:usersakadevdream-teamenvlibsite-packagessqlalchemyengineurl.py", line 270, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'mysql/dt_admin:dt2016@localhost/dreamteam_db'
I have all the requirements, running python3.5.3 in virtualenvwrapper, on the most recent Raspbian Stretch (Jan2018), but I always get this. Any hints?
Traceback (most recent call last):
File "scraper.py", line 8, in <module>
db = dataset.connect(settings.CONNECTION_STRING)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/dataset/__init__.py", line 41, in connect
ensure_schema=ensure_schema, row_type=row_type)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/dataset/database.py", line 53, in __init__
self.engine = create_engine(url, **engine_kwargs)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/sqlalchemy/engine/__init__.py", line 419, in create_engine
return strategy.create(*args, **kwargs)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py", line 50, in create
u = url.make_url(name_or_url)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/sqlalchemy/engine/url.py", line 205, in make_url
return _parse_rfc1738_args(name_or_url)
File "/home/pi/.virtualenvs/testtwitter_scrape/lib/python3.5/site-packages/sqlalchemy/engine/url.py", line 254, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name)
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string ''
Issue
I am learning Python Flask and I am working to a blog as personal project. I am using a combination of Flask and Sqlite but I am stuck because it seems that my system (I am using Windows 10) is not able to find the path to the database. This is my code:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite: ////C:/Users/admin/Desktop/Blog_Project/blog.db'
db = SQLAlchemy(app)
class Blogpost(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(50))
subtitle = db.Column(db.String(50))
author = db.Column(db.String(20))
date_posted = db.Column(db.DateTime)
content = db.Column(db.Text)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/post')
def post():
return render_template('post.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/prova')
def prova():
return render_template('prova.html')
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form["author"]
content = request.form['content']
post = Blogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted=datetime.now())
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
But when I try to add a post in the corresponding webpage, I get this error:
sqlalchemy.exc.ArgumentError
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'sqlite: ////C:/Users/admin/Desktop/Blog_Project/blog.db'
Actually the database should exist, since I see the file in my folder (the path is the one in the code)
Have you got any idea how I can solve the problem?
Solution
Try using double slashes:
sqlite: ////C:\Users\admin\Desktop\Blog_Project\blog.db
or if you want to stay on windows, use the windows formation:
sqlite: ////C:UsersadminDesktopBlog_Projectblog.db
you can learn more in this detailed answer: Windows path in Python
Answered By – shiny
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
Problem Description:
I am learning Python Flask and I am working to a blog as personal project. I am using a combination of Flask and Sqlite but I am stuck because it seems that my system (I am using Windows 10) is not able to find the path to the database. This is my code:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite: ////C:/Users/admin/Desktop/Blog_Project/blog.db'
db = SQLAlchemy(app)
class Blogpost(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(50))
subtitle = db.Column(db.String(50))
author = db.Column(db.String(20))
date_posted = db.Column(db.DateTime)
content = db.Column(db.Text)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/post')
def post():
return render_template('post.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/prova')
def prova():
return render_template('prova.html')
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form["author"]
content = request.form['content']
post = Blogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted=datetime.now())
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
But when I try to add a post in the corresponding webpage, I get this error:
sqlalchemy.exc.ArgumentError
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'sqlite: ////C:/Users/admin/Desktop/Blog_Project/blog.db'
Actually the database should exist, since I see the file in my folder (the path is the one in the code)
Have you got any idea how I can solve the problem?
Solution – 1
Try using double slashes:
sqlite: ////C:UsersadminDesktopBlog_Projectblog.db
or if you want to stay on windows, use the windows formation:
sqlite: ////C:UsersadminDesktopBlog_Projectblog.db
you can learn more in this detailed answer: Windows path in Python
Solution – 2
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///blog.db’
Solution – 3
For the convenience of Linux
and Windows
users, I have summarized the solutions for this problem on Windows
and Linux
:
from sqlalchemy import create_engine
# relative path on Linux: with three slashes
e = create_engine('sqlite:///relative/path/to/database.db')
# absolute path on Linux: with four slashes
e = create_engine('sqlite:////absolute/path/to/database.db')
# absolute path on Windows
e = create_engine('sqlite:///C:absolutepathtodatabase.db')
For detailed documents: SQLAlchemy 1.4 Documentation
#python #postgresql #flask
Вопрос:
from flask import Flask, jsonify
from flask import request
from slotscal import results
from flask_sqlalchemy import SQLAlchemy
import time
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'postgresql://postgres:test123@localhost:5432/flask'
db=SQLAlchemy(app)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hamza/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1094, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/home/hamza/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1086, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/home/hamza/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1017, in get_engine
return connector.get_engine()
File "/home/hamza/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 592, in get_engine
sa_url = make_url(uri)
File "/home/hamza/.local/lib/python3.8/site-packages/sqlalchemy/engine/url.py", line 694, in make_url
return _parse_rfc1738_args(name_or_url)
File "/home/hamza/.local/lib/python3.8/site-packages/sqlalchemy/engine/url.py", line 755, in _parse_rfc1738_args
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'postgresql:/test123@localhost/flask'
Комментарии:
1. Правильный URL-адрес см. в документах Postgres-psycopg2 .
2. @AdrianKlaver Та же ошибка.
3. Вам нужно добавить свое изменение в качестве обновления к вопросу.
4. Извините, попытался переустановить psycogp2 с необходимыми условиями sudo apt установить libpq-dev python3-dev, и это сработало. Спасибо. Вы должны ответить на этот вопрос.
Ответ №1:
Строка подключения должна быть строкой подключения libpq, синтаксис которой задокументирован в документации PostgreSQL.
Если вы используете форму URL-адреса, вы должны придерживаться RFC 1738. В частности, вам нужны две косые черты после postgresql:
:
postgresql://test123@localhost/flask