Flask Error When I run python program in pycharme - python

i have this error after run:
Traceback (most recent call last):
File "/home/user/PycharmProjects/third_project/flask_test.py", line 1, in <module>
from flask import Flask
File "/home/user/PycharmProjects/third_project/flask.py", line 1, in <module>
from flask import Fl
ImportError: cannot import name 'Fl' from partially initialized module 'flask' (most likely due to a circular import) (/home/user/PycharmProjects/third_project/flask.py)
Process finished with exit code 1
************************ the code :flask_test.py**************************
from flask import Flask
skills_app = Flask(__name__)
#skills_app.route("/")
def hompage():
return "hello flask"
#skills_app.route("/about")
def about():
return "hello flask/about"
if __name__=="__main__":
skills_app.run(debug=True)

Related

ModuleNotFoundError: No module named 'bin.strings'

when starting a telegram bot
python3 main.py
Traceback (most recent call last):
File "/home/tg_bot/main.py", line 6, in <module>
import database
File "/home/tg_bot/database.py", line 4, in <module>
from bin.strings import get_now_date
ModuleNotFoundError: No module named 'bin.strings'
there were no errors, suddenly appeared
example from bin strings
def get_now_date():
"""
Получение текущей даты
:return:
"""
now_data = datetime.now()
return now_data.strftime("%d/%m/%Y %H:%M:%S")

Getting multiple error while using flask-ask and ngrok with ROS

I'm trying to use flask-ask library and develope a skill that can make me able to control a robot in ROS with alexa vocal assistant. Python code named "alexa_interface.py" is here.
The skill id number is substituted with my skill id number.
While launching this command
python3 alexa_interface.py
I am getting the following code error.
Tried to install dependencies with pip but getting:
AttributeError: module 'lib' has no attribute 'ERR_load_RAND_strings'
Also notice that I am getting this error everytime I use pip to install something. Is pip broken? How can I adjust this?
Thank you.
#! /usr/bin/env python3
from flask import Flask
from ask_sdk_core.skill_builder import SkillBuilder
from flask_ask_sdk.skill_adapter import SkillAdapter
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
from ask_sdk_model.ui import SimpleCard
app = Flask(__name__)
class LaunchRequestHandler(AbstractRequestHandler):
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speech_text = "Ciao, come posso aiutarti?"
handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).set_should_end_session(
False)
return handler_input.response_builder.response`
skill_builder = SkillBuilder()
# Register your intent handlers to the skill_builder object
skill_builder.add_request_handler(LaunchRequestHandler())
skill_adapter = SkillAdapter(
skill=skill_builder.create(), skill_id="my-skill-id", app=app)
skill_adapter.register(app=app, route="/")
if __name__=='__main__':
app.run()
```
```
Traceback (most recent call last):
File "alexa_interface.py", line 2, in <module>
from flask import Flask
File "/home/toti/.local/lib/python3.8/site-packages/flask/__init__.py", line 14, in <module>
from jinja2 import escape
ImportError: cannot import name 'escape' from 'jinja2' (/home/toti/.local/lib/python3.8/site-packages/jinja2/__init__.py)
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module>
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module>
import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket
File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 1, in <module>
import requests
File "/home/toti/.local/lib/python3.8/site-packages/requests/__init__.py", line 52, in <module>
from .packages.urllib3.contrib import pyopenssl
File "/home/toti/.local/lib/python3.8/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 46, in <module>
import OpenSSL.SSL
File "/home/toti/.local/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
from OpenSSL import rand, crypto, SSL
File "/home/toti/.local/lib/python3.8/site-packages/OpenSSL/rand.py", line 213, in <module>
_lib.ERR_load_RAND_strings()
AttributeError: module 'lib' has no attribute 'ERR_load_RAND_strings'
Original exception was:
Traceback (most recent call last):
File "alexa_interface.py", line 2, in <module>
from flask import Flask
File "/home/toti/.local/lib/python3.8/site-packages/flask/__init__.py", line 14, in <module>
from jinja2 import escape
ImportError: cannot import name 'escape' from 'jinja2' (/home/toti/.local/lib/python3.8/site-packages/jinja2/__init__.py)
```

Run Python script unit testing - Selenium

I am a junior developer and totally new to Python and Selenium. I have to learn unit testing. They shared a small repository as an example. As required I installed Python and Selenium, but I don't know how to run. I have looked some tutorials, they just installed Python and Selenium, and added chromedriver, that's it. I have completed same steps, added PYTHONPATH and everything. But still getting errors.
My PYTHONPATH variable C:\Users\yanke\altrium-systemtests\altsys
Readme.md
System tests for Altrium frontend.
Install Python
export PYTHONPATH="."
python altsys/tests.py
tests.py
""Test altrium portal"""
import unittest
from selenium import webdriver
from altsys.selenium_helpers import sreenshot_on_fail
from altsys.page import AltriumPage
#sreenshot_on_fail()
class LoginTest(unittest.TestCase):
"""Test altrium portal login
Args:
unittest ([type]): [description]
"""
def setUp(self) -> None:
self.driver = webdriver.Chrome()
# self.driver = webdriver.Firefox()
self.page = AltriumPage(self.driver, 'https://alpha.altrium.sg/login')
def test_login(self):
"""Test login
"""
self.page.login(
'tdrobiszewski+st#gmail.com',
'TestPassword123!'
)
# SLACK_TOKEN = 'xoxb-1178000328886-3062418273846-EIxTJ17QSbELkwB7WnbfHuFr'
if __name__ == '__main__':
unittest.main()
When I run I am getting these errors:
Error
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\unittest\loader.py", line 34, in testFailure
raise self._exception
ImportError: Failed to import test module: tests
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\unittest\loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\Users\yanke\altrium-systemtests\altsys\tests.py", line 5, in <module>
from altsys.selenium_helpers import sreenshot_on_fail
File "C:\Users\yanke\altrium-systemtests\altsys\selenium_helpers.py", line 3, in <module>
from slack_sdk import WebClient
ModuleNotFoundError: No module named 'slack_sdk'
Ran 1 test in 0.006s
FAILED (errors=1)
Process finished with exit code 1
On Terminal
Traceback (most recent call last):
File "C:\Users\yanke\altrium-systemtests\altsys\tests.py", line 5, in <module>
from altsys.selenium_helpers import sreenshot_on_fail
ModuleNotFoundError: No module named 'altsys'

ModuleNotFoundError: No module named 'BaseHTTPServer'

So I am trying to follow a tutorial online on how to work with web.py, and I got it installed but unfortunately, using this piece of code yields a nasty error.
My Code...
import web
urls = (
'/(.*)', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self, name):
return "Hello", name, '. How are you today?'
if __name__== "__main__":
app.run()
MY ERROR:
C:\Users\User\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/User/PycharmProjects/Webprojects/main.py
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/Webprojects/main.py", line 15, in <module>
app.run()
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\web\application.py", line 312, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\web\wsgi.py", line 59, in runwsgi
return httpserver.runsimple(func, server_addr)
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\web\httpserver.py", line 154, in runsimple
func = LogMiddleware(func)
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\web\httpserver.py", line 296, in __init__
from BaseHTTPServer import BaseHTTPRequestHandler
ModuleNotFoundError: No module named 'BaseHTTPServer'
Process finished with exit code 1
That import line won't work in Python 3 which moved BaseHTTPServer to http.server
In your specific case you should update web.py to the current version that works with Python 3.

Flask and SQLAlchemy: No module named 'app' and NameError

Noob level here. It seems my models.py file can't import the db object created in init.py, but a db file (blog.db) is still being created. Since I can't use my model class (Entry(db.Model)) to add to the database from within the console (the db object itself works in the console), I think I'm importing incorrectly from within the models.py. On Python3 (venv), Linux.
Dir structure (relevant folders only, ex. no cache):
/folder/
/folder/app/
/folder/app/__init__.py
/folder/app/models.py
/folder/config.py (only includes the sqlite uri naming variable)
/folder/fakepy/etc (venv, with flask and flask_sqlalchemy)
/folder/run.py (starts server fine, but does show that 'common' sql track modifications warning twice after a restart. normal?)
__init__.py:
#!fakepy/bin/python3 (error happens with or without shebang(s))
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import models
models.py:
#!fakepy/bin/python3
from app import db
import re
import datetime
class Entry(db.Model):
__tablename__ = "post"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
slug = db.Column(db.String, unique=True)
content = db.Column(db.Text)
timestamp = db.Column(db.DateTime)
def __init__(self, title, content, slug=None, timestamp=None):
self.title = title
self.content = content
if slug is None:
self.slug = re.sub('[^\w]+', '-', self.title.lower())
if timestamp is None:
timestamp = datetime.utcnow()
self.timestamp = timestamp
config.py:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'blog.db')
Database is created... (console opened at /folder/, blog.db created at /folder/):
>>> from app import db
>>> db.create_all()
>>>
ERROR: name 'Entry' is not defined when app is imported from console
(fakepy) cha0#skyrim:~/folder$ python3
Python 3.4.3+ (etc removed for brevity)
>>> from app import app
(common sql track modifications warning, removed it for brevity)
>>> Entry()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
>>>
>>> from app import models
>>> Entry()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
>>>
>>> from app import Entry
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Entry'
>>>
ERROR: No module named 'app' when models.py is ran directly.
(fakepy) cha0#skyrim:~/folder/app$ python3 models.py
Traceback (most recent call last):
File "models.py", line 2, in <module>
from app import db
ImportError: No module named 'app'
(fakepy)
ERROR: No module named 'config' when init.py is ran directly.
I think this may be a separate issue though.
python3 __init__.py
Traceback (most recent call last):
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
__import__(import_name)
ImportError: No module named 'config'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "__init__.py", line 6, in <module>
app.config.from_object('config')
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/flask/config.py", line 162, in from_object
obj = import_string(obj)
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 443, in import_string
sys.exc_info()[2])
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/_compat.py", line 137, in reraise
raise value.with_traceback(tb)
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
__import__(import_name)
werkzeug.utils.ImportStringError: import_string() failed for 'config'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' not found.
Original exception:
ImportError: No module named 'config'
What I want:
From flask website.
>>>from yourapplication import User
>>> admin = User('admin', 'admin#example.com')
In my case-
>>>from app import Entry
>>>entry = Entry("title", "this is a post.")
from app.models import Entry
You must import Entry from the models module of the app.
You may also need to add relative imports in your __init__ for any custom modules.
add to your __init__
from .models import *
edit: Another useful debugging tip - is to use the dir() function to see what is included in a package. In your case, the imports are working so you can run something like
dir(app)
With an argument, attempt to return a list of valid attributes for that object.
for instance here is a returned list for a flask app I wrote.if You cant see your moudle here, add the import.

Categories