Flask migrate fails with extension not loaded - python

Initialization code
extensions.py
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from authentek.logger import log
db = SQLAlchemy()
migrate = Migrate()
bcrypt = Bcrypt()
cors = CORS(resources={r"/v1/*": {"origins": "*"}})
log.debug("in debug mode")
from authentek.extensions import db, migrate, bcrypt, cors
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
blueprint = Blueprint('api', __name__, url_prefix='/v1')
api.init_app(blueprint)
api.add_namespace(users_namespace)
api.add_namespace(auth_namespace)
if blueprint.name not in flask_app.blueprints.keys():
flask_app.register_blueprint(blueprint)
else:
flask_app.blueprints[blueprint.name] = blueprint
cors.init_app(flask_app)
db.app = flask_app
db.create_all()
bcrypt.init_app(flask_app)
if cli is True:
migrate.init_app(flask_app, db) # here it's registered
flask db migrate
2020-06-27 09:09:04,827 - authentek.logger - DEBUG - in debug mode
Traceback (most recent call last):
File "/usr/local/bin/flask", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask_migrate/cli.py", line 88, in migrate
rev_id)
File "/usr/local/lib/python3.7/site-packages/flask_migrate/__init__.py", line 175, in migrate
config = current_app.extensions['migrate'].migrate.get_config(
KeyError: 'migrate'
repository: https://github.com/eshta/authentek

You haven't initialized the migrate instance.
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
migrate.init_app(flask_app, db)
# ...
Also, remove db.create_all(), since you want Flask-Migrate to manage your database schema.

Related

NameError: name 'app' is not defined in Flask

FlaskWebDir
helloapp
__init__.py
templates
hello.py
main.py
__ init __.py:
from flask import Flask
from helloapp import routes
app = Flask(__name__)
if __name__=='__main__':
app.run()
routes.py:
from flask import render_template
#app.route("/")
def hello():
### code
#app.route("/user/<username>/")
def hello_user(username):
### code
#app.route("/users/")
def display_users():
###code
main.py:
from helloapp import app
$ flask run
* Serving Flask app "main.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "/home/as/FlaskWebDir/projenv/bin/flask", line 8, in <module>
sys.exit(main())
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 305, in __init__
self._load_unlocked()
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/as/FlaskWebDir/main.py", line 1, in <module>
from helloapp import app
File "/home/as/FlaskWebDir/helloapp/__init__.py", line 2, in <module>
from helloapp import routes
File "/home/as/FlaskWebDir/helloapp/routes.py", line 5, in <module>
#app.route("/")
NameError: name 'app' is not defined
In your routes, add:
# Previous import
from helloapp import app
#app.route('/')
def hello():
# ...
# ...
The app you are importing here is used in your decorators.

ValueError: invalid literal for int() with base 10: '\\Users\\Padma Jain\\python\\flask\\flask_login\\app\\data.sqlite'

I am learning flask-login package. When I run flask db init, I don't get any errors. But this is the error i get when i run flask db migrate -m "creating users":
Traceback (most recent call last):
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python37\Scripts\flask.exe\__main__.py", line 7, in <module>
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask\cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask\cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask\cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_migrate\cli.py", line 92, in migrate
rev_id, x_arg)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_migrate\__init__.py", line 96, in wrapped
f(*args, **kwargs)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_migrate\__init__.py", line 212, in migrate
version_path=version_path, rev_id=rev_id)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\alembic\command.py", line 212, in revision
script_directory.run_env()
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\alembic\script\base.py", line 490, in run_env
util.load_python_file(self.dir, "env.py")
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\alembic\util\pyfiles.py", line 97, in load_python_file
module = load_module_py(module_id, path)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\alembic\util\compat.py", line 182, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 25, in <module>
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
return self.get_engine()
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\flask_sqlalchemy\__init__.py", line 554, in get_engine
sa_url = make_url(uri)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\sqlalchemy\engine\url.py", line 229, in make_url
return _parse_rfc1738_args(name_or_url)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\sqlalchemy\engine\url.py", line 288, in _parse_rfc1738_args
return URL(name, **components)
File "c:\users\padma jain\appdata\local\programs\python\python37\lib\site-packages\sqlalchemy\engine\url.py", line 71, in __init__
self.port = int(port)
ValueError: invalid literal for int() with base 10: '\\Users\\Padma Jain\\python\\flask\\flask_login\\app\\data.sqlite'
Here is my app.py
# app.py
from app import app, db
from flask import render_template, flash, redirect, request, url_for
from flask_login import login_user, logout_user, login_required
from app.models import User
from app.forms import RegistrationForm, LoginForm
#app.route("/")
def home():
return render_template("index.html")
#app.route("/welcome")
#login_required
def welcome_user():
return render_template("welcome-user.html")
#app.route("/logout")
#login_required
def logout():
logout_user()
flash("Logged out successfully")
return redirect(url_for('home'))
#app.route("/login", methods = ["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user.check_password(form.password.data) and user is not None:
login_user(user)
flash("Logged in successfully!")
next = request.args.get("next")
if next == None or not next[0] == '/':
next = url_for('welcome_user')
return redirect(next)
return render_template("login.html",form=form)
#app.route("/register",methods=["GET","POST"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
flash("Created account successfully")
return redirect(url_for('login'))
return render_template("register.html")
if __name__ == "__main__":
app.run(debug=True)
init.py:
# __init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
login_manager = LoginManager()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisismysecretkeydontstealit'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app, db)
login_manager.init_app(app)
login_manager.login_view = 'login'
models.py
# models.py
from app import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
#login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
email = db.Column(db.String(64),unique = True, index = True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
def __init__(self):
self.email = email
self.username = username
self.password_hash = generate_password_hash(password)
def check_password(self):
return check_password_hash(self.check_password_hash, password)
Please help me
It looks like you have an incorrect database URL. If I'm not mistaken, Flask login uses the SQLAlchemy python framework under the hood to connect to databases, so your URL should satisfy the format described in the SQLAlchemy's documentation
Try replacing the line
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' + os.path.join(basedir,'data.sqlite')
with
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite+pysqlite:///' + os.path.join(basedir,'data.sqlite')

IndexError from eureka-flask

So I try to register simple Flask service with Eureka by installing a client. I did everything by the instruction from there: https://github.com/elviejokike/flask-eureka
The code I try to run:
from flask import jsonify
from flask_eureka import Eureka
from flask_eureka.eureka import eureka_bp
app = Flask(__name__)
eureka = Eureka(app)
eureka.register_service(name="my-flask-service")
app.register_blueprint(eureka_bp)
#app.route('/model')
def hello_world():
a = {"text": "I am model service!"}
return jsonify(a)
if __name__ == '__main__':
app.run()
Instead of initializing the service I get this pile of errors:
FLASK_ENV = development
FLASK_DEBUG = 0
In folder C:/Users/HP/PycharmProjects/models-service
C:\Users\HP\PycharmProjects\models-service\venv\Scripts\python.exe -m flask run
* Serving Flask app "app.py"
* Environment: development
* Debug mode: off
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\__main__.py", line 15, in <module>
main(as_module=True)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 305, in __init__
self._load_unlocked()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\HP\PycharmProjects\models-service\app.py", line 9, in <module>
eureka.register_service(name="my-flask-service")
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\eureka.py", line 51, in register_service
eureka_client = EurekaClient(name=name, host_name=host_name,
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\eurekaclient.py", line 95, in __init__
host_info = HostInfo().get()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\hostinfo.py", line 34, in get
'IPv4': self.ipv4(),
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\hostinfo.py", line 53, in ipv4
ipv4 = ipv4.split(':')[1]
IndexError: list index out of range
Process finished with exit code 1
Every library is installed through pip, code without eureka runs correctly. I think it might be related to OS forbidding an access to network, but I'm not quite sure and need a hand.

How can this SSL error using PROTOCOL_TLSv1_2 be solved?

I am creating an API using Python and the flask library. I have some problems with SSL. I am running the API on a Ubuntu 16.04.6 LTS server.
from flask import Flask
from flask import request
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.load_cert_chain('PATH_TO_PUBLIC_KEY','PATH_TO_PRIVATE_KEY')
#app.route('/example', methods=['POST'])
def sayHallo():
return "Hallo!"
if __name__ == '__main__':
serving.run_simple("0.0.0.0", 5000, app, ssl_context=context)
The API and its connection works using http, but adding SSL to the code gives me the error:
Traceback (most recent call last):
File "/usr/local/bin/flask", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 966, in main
cli.main(prog_name="python -m flask" if as_module else None)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1137, in inv oke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 956, in invo ke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invo ke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invo ke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 848, in run_c ommand
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 305, in __ini t__
self._load_unlocked()
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 330, in _load _unlocked
self._app = rv = self.loader()
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 388, in load_ app
app = locate_app(self, import_name, name)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 240, in locat e_app
__import__(module_name)
File "/var/www/api/app.py", line 7, in <module>
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2'
According to [PyOpenSSL]: class OpenSSL.SSL.Context(method):
Parameters: method - One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or TLSv1_METHOD.
So, you should use:
context = SSL.Context(SSL.TLSv1_2_METHOD)

Error running OpenTok Server Code (Python)

I have problem running flask run for OpenTok server code. How can I eradicate the error? Thanks in advance.
This is the error:
(opentokenv) ➜ opentok-server python -m flask run
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/Library/Python/2.7/site-packages/flask/__main__.py", line 15, in <module>
main(as_module=True)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "/Library/Python/2.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/Library/Python/2.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Library/Python/2.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/Library/Python/2.7/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 423, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 152, in __init__
self._load_unlocked()
File "/Library/Python/2.7/site-packages/flask/cli.py", line 176, in _load_unlocked
self._app = rv = self.loader()
File "/Library/Python/2.7/site-packages/flask/cli.py", line 237, in load_app
rv = locate_app(self.app_import_path)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 90, in locate_app
__import__(module)
File "/Users/azambaderi/Documents/Web_Projects/opentok-server/opentok.py", line 2, in <module>
from opentok import OpenTok
ImportError: cannot import name OpenTok
This is the Python code:
from flask import Flask, render_template
from opentok import OpenTok
import os
try:
api_key = os.environ['API_KEY']
api_secret = os.environ['API_SECRET']
except Exception:
raise Exception('You must define API_KEY and API_SECRET environment variables')
app = Flask(__name__)
opentok = OpenTok(api_key, api_secret)
session = opentok.create_session()
#app.route("/")
def hello():
key = api_key
session_id = session.session_id
token = opentok.generate_token(session_id)
return render_template('index.html', api_key=key, session_id=session_id, token=token)
if __name__ == "__main__":
app.debug = True
app.run()
I tried your code and it worked for me, until I changed the filename to opentok.py (from the stack trace it appears that is the name you are using).
I think the quickest solution here is to change your filename from opentok.py to something else as it conflicting with the library name. (Don't forget to remove the opentok.pyc file too).
If you wish to keep the name you should see this answer about Absolute and Relative imports

Categories

Resources