I am trying to build my first Webb app using Django. I’m using my iPad because I am on the move a lot. Anyways, I’m trying to follow Django’s instructions for building a poll application. I got the server running but when i made the changes that should have printed the Hello World but its now its giving me a ModuleNotFoundError.
I’ve tried copy and pasting the lines of code from Django’s website and I’ve tried to type it in on my own.
ModuleNotFoundError: No module named 'WellnessApp'
import os
`import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WellnessProject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
#if __name__ == '__main__':
# main()
if __name__ == '__main__':
import background as bg
with bg.BackgroundTask() as b:
main()`
Related
import configparser
from tkinter import *
from tkinter import filedialog,messagebox
from tkinter.filedialog import asksaveasfile
from customtkinter import *
import os
import time
import wikipedia
config=configparser.ConfigParser()
config.read("config.ini")
def change_config():
messagebox.showinfo("Information","App is going to restart in few seconds")
print(mode.get())
print(color.get())
global location
config.set("THEME","mode",str(mode.get()))
config.set("VOICE","voice",str(gender.get()))
if color.get() =="pink":
location="C:/Users/DELL/Documents/python programs/notepad/custom_theme.json"
config.set("THEME","color",location)
else :
config.set("THEME","color",color.get())
with open("config.ini","w") as configfile:
config.write(configfile)
restart()
def main():
global root,label,frame1,config_color,config_mode,config_gender
root=CTk()
root.geometry("700x600")
root.resizable(0,0)
root.title("Notepad")
frame1=CTkFrame(root,width=150,height=580)
frame1.pack_propagate(False)
frame1.place(x=10,y=10)
config_color=config.get("THEME","color")
config_mode=config.get("THEME","mode")
config_gender=config.get("VOICE","voice")
set_appearance_mode(config_mode)
set_default_color_theme(config_color)
label=CTkLabel(root,text="File",width=520,height=40,font=("Algerian",30))
label.place(x=170,y=10)
global S
global text_area
text_area=CTkTextbox(root,height=580,width=520,)
text_area.place(x=170,y=60)
global button,commands,button_text
button_text="Settings"
commands=settings
button=CTkButton(frame1,text=button_text,command=settings)
button.pack(padx=10,pady=10)
root.mainloop()
def settings():
global submit,mode,color,config_color,config_mode,gender
window=CTkToplevel(root)
window.title("Settings")
window.geometry("200x300")
label1=CTkLabel(window,text="Mode").pack(pady=5)
mode=CTkOptionMenu(window,values=["light","dark"])
mode.pack(pady=5,padx=5,anchor=CENTER)
label2=CTkLabel(window,text="Color").pack(pady=5)
color=CTkOptionMenu(window,values=["pink","blue","green","dark-blue"])
color.pack(pady=5)
label3=CTkLabel(window,text="speech-gender").pack(pady=5)
gender=CTkOptionMenu(window,values=["male","female"])
gender.pack(pady=5)
submit=CTkButton(window,text="Submit",command=change_config)
submit.pack(pady=20)
window.mainloop()
if __name__=="__main__":
def restart():
time.sleep(5)
root.destroy()
main()
main()
I want to create a notepad , where we can change themes and colors.
I have made config.ini file where i save the current mode, color and the voice type for the notepad ( voicetype is for text-to-speech functionality that i have added here ) becuase while using customtkinter we can set default color theme and cannot change it once initialized in a program.
The program now save the selected preferences in config.ini file and grab it when run again.
I want the program to run again itself without having the need to explicitly run it again.
Though program is running i am still getting this error at backend:
invalid command name "2912423726080check_dpi_scaling"
while executing
"2912423726080check_dpi_scaling"
("after" script)
invalid command name "2912423728512update"
while executing
"2912423728512update"
("after" script)
invalid command name "2912423728448<lambda>"
while executing
"2912423728448<lambda>"
("after" script)
I want to know what this error means so that the users might not face problem in future while using this app.
Thanks in advance for helping.
I try to run the below following code using python3 recv.py on visual studio code but I'm getting the following error
Traceback (most recent call last):
File "recv.py", line 2, in <module>
from azure.eventhub.aio import EventHubConsumerClient
ModuleNotFoundError: No module named 'azure'
import asyncio
from azure.eventhub.aio import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore
async def on_event(partition_context, event):
# Print the event data.
print("Received the event: \"{}\" from the partition with ID: \"{}\"".format(event.body_as_str(encoding='UTF-8'), partition_context.partition_id))
# Update the checkpoint so that the program doesn't read the events
# that it has already read when you run it next time.
await partition_context.update_checkpoint(event)
async def main():
# Create an Azure blob checkpoint store to store the checkpoints.
checkpoint_store = BlobCheckpointStore.from_connection_string("connection_string", "containername")
# Create a consumer client for the event hub.
client = EventHubConsumerClient.from_connection_string("connection_string", consumer_group="$Default", eventhub_name="eventhubinstance", checkpoint_store=checkpoint_store)
async with client:
# Call the receive method. Read from the beginning of the partition (starting_position: "-1")
await client.receive(on_event=on_event, starting_position="-1")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# Run the main method.
loop.run_until_complete(main())
I try to execute the file on my iTerm terminal and it's working fine. Can you tell me why it is n ot working in vscode?
I'm using Python 3.7.9
I have installed the package using pip3 install azure-eventhub (I have also tried with just pip) but the modules are still interpreting as missing whereas there are not.
Using pip show azure-eventhub WARNING: Package(s) not found: azure-eventhub but it is there I can see the package in /usr/local/lib/python3.10/site-packages
Why I'm getting this error --> AttributeError: module 'collections' has no attribute 'namedtuple'. Whats wrong with my code..
I'm using python 3.5.2 on windows. When I execute my code on IDLE it can run - show up the kivy window, but when I execute C:\POS\operator\python operator.py it failed.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class OperatorWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class OperatorApp(App):
def build(self):
return OperatorWindow()
if __name__ == "__main__":
OperatorApp().run()
It looks like your file name is at fault here since there's also a standard library module called operator. I've got the same error but when I renamed your sample code from operator.py to test.py, it worked normally.
I have the following problem.
I'd like to run tests on the local flask server before deploying to production. I use pytest for that. My conftest.py looks like that for the moment:
import pytest
from toolbox import Toolbox
import subprocess
def pytest_addoption(parser):
"""Add option to pass --testenv=local to pytest cli command"""
parser.addoption(
"--testenv", action="store", default="exodemo", help="my option: type1 or type2"
)
#pytest.fixture(scope="module")
def testenv(request):
return request.config.getoption("--testenv")
#pytest.fixture(scope="module")
def testurl(testenv):
if testenv == 'local':
return 'http://localhost:5000/'
else:
return 'https://api.domain.com/'
This allows me to test the production api by typing the command pytest and to test a local flask server by typing pytest --testenv=local
This code WORKS flawlessly.
My problem is that I have to manually instantiate the local flask server from the terminal each time I want to test locally like this:
source ../pypyenv/bin/activate
python ../app.py
Now I wanted to add a fixture that initiates a terminal in the background at the beginning of the tests and closes the server down after having finished testing. After a lot of research and testing, I still cannot get it to work. This is the line I added to the conftest.py:
#pytest.fixture(scope="module", autouse=True)
def spinup(testenv):
if testenv == 'local':
cmd = ['../pypyenv/bin/python', '../app.py']
p = subprocess.Popen(cmd, shell=True)
yield
p.terminate()
else:
pass
The errors I get are from the requests package that says that there is no connection/ refused.
E requests.exceptions.ConnectionError:
HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded
with url: /login (Caused by
NewConnectionError(': Failed to establish a new connection:
[Errno 111] Connection refused',))
/usr/lib/python3/dist-packages/requests/adapters.py:437:
ConnectionError
This means for me that the flask server under app.py is not online. Any suggestions? I am open to more elegant alternatives
For local testing the Flask test_client is a more elegant solution. See the docs on Testing. You can create a fixture for the test_client and create test requests with that:
#pytest.fixture
def app():
app = create_app()
yield app
# teardown here
#pytest.fixture
def client(app):
return app.test_client()
And use it like this:
def test_can_login(client):
response = client.post('/login', data={username='username', password='password'})
assert response.status_code == 200
If the only problem are the manual steps, maybe consider a bash script that does your manual setup for you and after that executes pytest.
I am using the following for this purpose so that testing configuration is also preserved in the test server
#pytest.fixture(scope="session")
def app():
db_fd, db_path = tempfile.mkstemp()
app = create_app({
'TESTING': True,
'DATABASE': db_path
})
yield app
os.close(db_fd)
os.unlink(db_path)
from flask import request
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
#pytest.fixture
def server(app):
#app.route('/shutdown',methods=('POST',))
def shutdown():
shutdown_server()
return 'Shutting down server ...'
import threading
t = threading.Thread(target=app.run)
yield t.start()
import requests
requests.post('http://localhost:5000/shutdown')
References
https://flask.palletsprojects.com/en/1.1.x/tutorial/tests/
How do I terminate a flask app that's running as a service?
How to stop flask application without using ctrl-c
With a bash script (thanks #ekuusela) I now finally succeeded in what I wanted.
I added a fixture that calls the bashscript spinserver.sh in a new terminal window. This works in ubuntu, the command is different in different environments (see Execute terminal command from python in new terminal window? for other environments).
#pytest.fixture(scope="session", autouse=True)
def client(testenv):
if testenv != 'local':
pass
else:
p = subprocess.Popen(['gnome-terminal', '-x', './spinserver.sh'])
time.sleep(3)
yield
Here the very simple bashscript
#!/bin/bash
cd ..
source pypyenv/bin/activate
python app.py
The sleep command is necessary because the server takes some time to
initialize.
Don't forget to make your bash script executable (chmod
u+x spinserver.sh)
I tried to do a teardown after yield, but p.kill does not really
close the window. This is acceptable for me as it does not matter
if I have to manually close a terminal window & I can even see
flask debugging if necessary
I have a python module with the following layout:
foo
| __init__.py
| __main__.py
| bar.py
__init__.py is empty.
Content of foo/bar.py:
from flask import Flask
app = Flask(__name__)
def baz(): pass
When running python3 -m foo i get confusing results.
Contents of foo/__main__.py
# Results in a ModuleNotFoundError: No module named 'foo'
from foo.bar import app
app.run()
# Raises no error and correctly prints the type
from foo.bar import app
print(type(app))
# Also runs without an error
from foo.bar import baz
baz()
Why is it possible to import and execute a function from this module, but when trying to do the same with a flask app it results in a ModuleNotFoundError?
I just can't see any way this makes any sense.
Edit:
The error is persistent even with this code:
from foo.bar import app
print(type(app))
app.run()
Output:
<class 'flask.app.Flask'>
* Serving Flask app "foo.bar" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/home/user/projects/ftest/foo/__main__.py", line 1, in <module>
from foo.bar import app
ModuleNotFoundError: No module named 'foo'
So, obviously the module can be imported, because type(app) works just fine and flask does start. It seems like flask does a reload and is messing around with imports somehow.
Edit 2:
I turned debug mode off and it works just fine.
This error only occurs if you set export FLASK_DEBUG=True or explicitly enable debug via app.config["DEBUG"] = True
It turns out it's a bug in werkzeug.
The code works as expected if werkzeug's reloader is disabled.
How to reproduce the behaviour
Directory structure:
foo
| __init__.py
| __main__.py
Content of __init__.py:
from flask import Flask
app = Flask(__name__)
app.config["DEBUG"] = True
Content of __main__.py:
from foo import app
app.run()
If we run it:
$python3 -m foo
* Serving Flask app "foo" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/home/user/projects/ftest/foo/__main__.py", line 1, in <module>
from foo import app
ModuleNotFoundError: No module named 'foo'
If we change __main__.py:
from foo import app
app.run(use_reloader=False)
Everything works just fine.
What's going on
The problem is in werkzeug._reloader.ReloaderLoop.restart_with_reloader. It calls a subprocess with the arguments provided by werkzeug._reloader._get_args_for_reloading but this function does not behave as expected when executing a package via the -m switch.
def _get_args_for_reloading():
"""Returns the executable. This contains a workaround for windows
if the executable is incorrectly reported to not have the .exe
extension which can cause bugs on reloading.
"""
rv = [sys.executable]
py_script = sys.argv[0]
if os.name == 'nt' and not os.path.exists(py_script) and \
os.path.exists(py_script + '.exe'):
py_script += '.exe'
if os.path.splitext(rv[0])[1] == '.exe' and os.path.splitext(py_script)[1] == '.exe':
rv.pop(0)
rv.append(py_script)
rv.extend(sys.argv[1:])
return rv
In our case it returns ['/usr/local/bin/python3.7', '/home/user/projects/ftest/foo/__main__.py']. This is because sys.argv[0] is set to the full path of the module file but it should return ['/usr/local/bin/python3.7', '-m', 'foo']` (At least from my understanding it should and it works this way).
I have no good idea on how to fix this behaviour, or if it is something that need to be fixed. It just seems weird to me that I'm the only one that has encountered this problem, since it doesn't seem too much of a corner case to me.
Adding the following line before app.run() works around the werkzeug reloader bug:
os.environ['PYTHONPATH'] = os.getcwd()
Thanks to #bootc for the tip! https://github.com/pallets/flask/issues/1246
Have you tried from foo import app in your main.py file?