How can this SSL error using PROTOCOL_TLSv1_2 be solved? - python

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)

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.

Error: Directory migrations already exists and is not empty from flask db init

I am using Postgres DB with Flask migration. I have changed a table name and want to upgrade it to my local & then remote.
Init give:
flask db init
Python-dotenv could not parse statement starting at line 4
Python-dotenv could not parse statement starting at line 5
Python-dotenv could not parse statement starting at line 6
Error: Directory migrations already exists and is not empty
Migrate gives:
(env) (base) Daniyal#Daniyals-MacBook-Pro Website % flask db migrate
Python-dotenv could not parse statement starting at line 4
Python-dotenv could not parse statement starting at line 5
Python-dotenv could not parse statement starting at line 6
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/revision.py:152: UserWarning: Revision 6ee19758a13a referenced from 6ee19758a13a -> 2e8e5e007c0a (head), empty message is not present
util.warn(
Traceback (most recent call last):
File "/Users/Daniyal/Startup/Website/env/bin/flask", line 8, in <module>
sys.exit(main())
File "/Users/Daniyal/Startup/Website/env/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 "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/flask/cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/flask_migrate/cli.py", line 89, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/flask_migrate/__init__.py", line 96, in wrapped
f(*args, **kwargs)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/flask_migrate/__init__.py", line 210, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/command.py", line 214, in revision
script_directory.run_env()
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/base.py", line 489, in run_env
util.load_python_file(self.dir, "env.py")
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/util/pyfiles.py", line 98, in load_python_file
module = load_module_py(module_id, path)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/util/compat.py", line 184, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations/env.py", line 96, in <module>
run_migrations_online()
File "migrations/env.py", line 90, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/runtime/environment.py", line 846, in run_migrations
self.get_context().run_migrations(**kw)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/runtime/migration.py", line 511, in run_migrations
for step in self._migrations_fn(heads, self):
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/command.py", line 190, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/autogenerate/api.py", line 442, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/autogenerate/api.py", line 454, in _run_environment
self.script_directory.get_revisions("heads")
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/base.py", line 227, in get_revisions
return self.revision_map.get_revisions(id_)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/revision.py", line 321, in get_revisions
resolved_id, branch_label = self._resolve_revision_number(id_)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/revision.py", line 501, in _resolve_revision_number
self._revision_map
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/util/langhelpers.py", line 230, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/Users/Daniyal/Startup/Website/env/lib/python3.8/site-packages/alembic/script/revision.py", line 156, in _revision_map
down_revision = map_[downrev]
KeyError: '6ee19758a13a'
I am not sure why upgrading such a trivial change to DB's schema has to be such a hassle.
I would really appreciate your help on how I can make such change.

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.

ImportError: No module named functools_lrc_cache (discord.py bot)

I'm trying to set up a Discord modmail bot and host it on my Raspberry Pi, however I seem to be getting a traceback error that ends with ImportError: No module named functools_lrc_cache. I'm using Python 3.7 and pipenv to run the bot.py file. What could I do to resolve it?
Here below is the full Traceback error and the steps I'm following for selfhosting the bot: https://taaku18.github.io/modmail/local-hosting/
Traceback (most recent call last):
File "/home/pi/.local/bin/pipenv", line 10, in <module>
sys.exit(cli())
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 1236, in invoke
return Command.invoke(self, ctx)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/cli/command.py", line 204, in cli
clear=state.clear,
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/core.py", line 580, in ensure_project
pypi_mirror=pypi_mirror,
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/core.py", line 498, in ensure_virtualenv
python = ensure_python(three=three, python=python)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/core.py", line 388, in ensure_python
path_to_python = find_a_system_python(python)
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/core.py", line 347, in find_a_system_python
from .vendor.pythonfinder import Finder
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/pythonfinder/__init__.py", line 10, in <module>
from .models import SystemPath, WindowsFinder
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/pythonfinder/models/__init__.py", line 11, in <module>
from ..utils import KNOWN_EXTS, unnest
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/pythonfinder/utils.py", line 17, in <module>
from .compat import Path, lru_cache, TimeoutError # noqa
File "/home/pi/.local/lib/python2.7/site-packages/pipenv/vendor/pythonfinder/compat.py", line 15, in <module>
from backports.functools_lru_cache import lru_cache # type: ignore # noqa
ImportError: No module named functools_lru_cache

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