The run time error by import python module - python-3.x

I am trying to make correctly import the function "mmenu" from another module
I got a run time error:
Traceback (most recent call last):
File "path.../venv/src/routes.py", line 4, in <module>
from venv.src.main_menu import mmenu
ModuleNotFoundError: No module named 'venv.src'
after Java this Python is a bit of a mystery to me :)
I have 2 files in the same "src" directory
main_menu.py
def mmenu():
menu = [{"name": "HOME", "url": "home"},
{"name": "fooo", "url": "foo"},
{"name": "bar", "url": "bar"},
{"name": "CONTACT", "url": "contact"}]
return menu
routes.py
from flask import Flask, render_template, request, flash, session, redirect, abort
from jinja2 import Template
from flask.helpers import url_for
from venv.src.main_menu import mmenu
app = Flask(__name__)
menu = mmenu
#app.route("/")
#app.route("/index")
def index():
# return "index"
print("loaded" + url_for('index'))
return render_template('index.html', title="Index page", menu=menu)
# ...
if __name__ == "__main__":
app.run(debug=True)
import was generated by IDE like:
from venv.src.parts.main_menu import mmenu

Your IDE (which IDE?) is likely misconfigured if it generates imports like that.
The venv itself, nor any src directory within them, shouldn't be within import paths.
You never mention you have a parts/ package, but from the import I'll assume you do, and your structure is something like
venv/
src/ # source root
routes.py
parts/ # parts package
__init__.py # (empty) init for parts package
main_menu.py
With this structure, main_menu is importable as parts.main_menu from routes.py assuming you start the program with python routes.py.
If you have __init__.py files in venv/ and/or src/, get rid of them; you don't want those directories to be assumed to be Python packages.

Related

Vscode python file runs fine but ModuleNotFoundError is thrown when code-runner is used

Hello I have the following directory structure for my project in vscode:
--- my_programs/----|
|--my_code/----|
|__tests/
|
|__libs/my_package/classes.py
|
|__main/main.py
When I run main.py in the vscode terminal it runs fine. As soon as I run it using "Run Code" (which is an extension) it complains about the following:
`
Running] /Users/username/my_programs/venv/bin/python -u "/Users/username/my_programs/my_code/main/main.py"
Traceback (most recent call last):
File "/Users/username/my_programs/my_code/main/main.py", line 2, in <module>
from libs.my_package.classes import MyClass
ModuleNotFoundError: No module named 'libs'
`
main.py looks like this:
import os
from libs.my_package.classes import MyClass
dir_path = os.path.dirname(os.path.realpath(__file__))
print (dir_path)
cwd = os.getcwd()
print(cwd)
os.chdir(dir_path)
cwd = os.getcwd()
print (cwd)
m = MyClass("Hello Hello")
print(m)
My settings.json looks like the following:
{
"terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}/my_code"},
"python.envFile": "${workspaceFolder}/.vscode/env",
"python.analysis.extraPaths": [
"my_programs",
],
"python.testing.pytestArgs": [
"my_code"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.cwd": "${workspaceFolder}",
"python.terminal.activateEnvironment": true,
"python.terminal.activateEnvInCurrentTerminal": true,
"code-runner.fileDirectoryAsCwd": false,
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
},
}
Why does it work when I click "Run Python File" and not when I do "Run Code"? FYI, it also works manually from the terminal.

Issue with circular import in Django tutorials?

I am getting a circular import error with a basic Django page setup and I have no idea why. Am following the guides of at least 4 or 5 different tutorials with the same result.
I have varied the syntax in the webapps urls.py to no avail. Any ideas ?
mainproject
urls.py file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('members/', include('members.urls')),
path('admin/', admin.site.urls),
]
webapp
Views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello world!")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Error
"/Users/Desktop/website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 706, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from '/Users/Desktop/website/main/members/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.

Why the error occured when i tried to send a POST request with QWebEngineHttpRequest (PyQt5)?

I try to get JSON Object from source, but getting only errors.
Now I'm trying to understand what I'm doing wrong.
This code works well with other resources.
Maybe It`s not problem with code, but with web-source.
import sys
import json
from PyQt5.QtCore import QByteArray, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineCore import QWebEngineHttpRequest
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineSettings
from pprint import pprint
def on_load_finished():
"""Handle response"""
engine.toPlainText(handle_to_html) # get json
def handle_to_html(html):
"""Handle html"""
print(html)
QApplication.quit()
if __name__ == "__main__":
app = QApplication(sys.argv)
engine = QWebEnginePage()
url = "https://sportsapi.betway.com/api/Events/V2/GetEvents"
request = QWebEngineHttpRequest(url=QUrl(url), method=QWebEngineHttpRequest.Post)
request.setHeader(QByteArray(b"Content-Type"), QByteArray(b"application/json"))
payload = {
"LanguageId": 1,
"ClientTypeId": 2,
"BrandId": 3,
"JurisdictionId": 1,
"ClientIntegratorId": 1,
"ExternalIds": [9032262, 9038528, 9037778],
"MarketCName": "win-draw-win",
"ScoreboardRequest": {"ScoreboardType": 3, "IncidentRequest": {}},
"BrowserId": 3,
"OsId": 3,
"ApplicationVersion": "",
"BrowserVersion": "97.0.4692.99",
"OsVersion": "NT 10.0",
"SessionId": "null",
"TerritoryId": 227,
"CorrelationId": "06779075-21e2-4ba8-8e91-d71a981621fe",
"VisitId": "d1088cdf-13a8-42d0-be90-b34fd1332c36",
"ViewName": "sports",
"JourneyId": "833a4c0c-3354-499f-9d52-949df6d159f9",
}
request.setPostData(bytes(json.dumps(payload), "utf-8"))
engine.load(request)
engine.loadFinished.connect(on_load_finished)
app.exec_()
Errors are looks like
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
</Error>
Maybe It`s not problem with code, but with web-source.

Error on deploying Python app to AWS Lambda

I have built a Python-Tornado app and am trying to deploy it to AWS Lambda using zappa. But, I am getting an error Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.
My folder structure inside the root folder is :
├── amortization.py
├── config.py
├── dmi-amort-dev-1557138776.zip
├── main.py
├── requirements.txt
├── venv
│   ├── bin
│  
└── zappa_settings.json
zappa deploy dev gives me :
Calling deploy for stage dev..
Downloading and installing dependencies..
- pandas==0.24.2: Using locally cached manylinux wheel
- numpy==1.16.3: Using locally cached manylinux wheel
- sqlite==python3: Using precompiled lambda package
Packaging project as zip.
Uploading dmi-amort-dev-1557143681.zip (30.8MiB)..
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 32.3M/32.3M [00:19<00:00, 1.94MB/s]
Scheduling..
Scheduled dmi-amort-dev-zappa-keep-warm-handler.keep_warm_callback with expression rate(4 minutes)!
Uploading dmi-amort-dev-template-1557143718.json (1.5KiB)..
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1.56K/1.56K [00:00<00:00, 10.6KB/s]
Waiting for stack dmi-amort-dev to create (this can take a bit)..
75%|█████████████████████████████████████████████████████████████████████████████████████████████████████▎ | 3/4 [00:09<00:04, 5.00s/res]
Deploying API Gateway..
Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.
zappa tail gives me
Traceback (most recent call last):
File "/var/task/handler.py", line 602, in lambda_handler
return LambdaHandler.lambda_handler(event, context)
File "/var/task/handler.py", line 245, in lambda_handler
handler = cls()
File "/var/task/handler.py", line 142, in __init__
wsgi_app_function = getattr(self.app_module, self.settings.APP_FUNCTION)
AttributeError: module 'main' has no attribute 'app'
zappa_settings.json:
{
"dev": {
"app_function": "main.app",
"aws_region": "ap-south-1",
"profile_name": "default",
"project_name": "dmi-amort",
"runtime": "python3.6",
"s3_bucket": "zappa-mekp457ye",
"manage_roles": false,
"role_name": "lambda-role",
}
}
main.py:
import tornado.web
from tornado.ioloop import IOLoop
from tornado.web import MissingArgumentError
from config import get_arguments
from amortization import get_amort_schedule
class MainHandler(tornado.web.RequestHandler):
def prepare(self):
"""Checking if all the required parameters are present."""
if self.request.method != 'POST':
self.write_error(status_code=405, message="Method not allowed")
return
self.parameters = dict()
for key in get_arguments():
try:
self.parameters[key] = self.get_argument(key)
except MissingArgumentError:
self.write_error(status_code=400,
message="Missing Argument(s)")
return
# checking if 'label' is provided
if 'label' in self.request.arguments.keys():
self.parameters['label'] = self.get_argument('label')
# Set up response dictionary.
self.response = dict()
def get(self, *args, **kwargs):
self.write_error(status_code=405, message="Method not allowed")
def post(self, *args, **kwargs):
"""Executes the main logic part."""
self.response = get_amort_schedule(self.parameters)
self.write_json()
def set_default_headers(self):
"""Sets content-type as 'application/json' for response as JSON."""
self.set_header('Content-Type', 'application/json')
def write_error(self, status_code, **kwargs):
"""Invokes when error occurs in processing the request."""
if 'message' not in kwargs:
if status_code == 405:
kwargs['message'] = 'Invalid HTTP method.'
else:
kwargs['message'] = 'Unknown error.'
kwargs["error"] = True
self.set_status(status_code=status_code)
self.response = dict(kwargs)
self.write_json()
def write_json(self):
"""Responsible for writing the response."""
if "status" in self.response:
self.set_status(self.response.get("status"))
self.set_default_headers()
self.write(self.response)
self.finish()
def main():
app = tornado.web.Application([
(r'/', MainHandler),
], debug=True)
# server = HTTPServer(app)
# server.bind(8888)
# server.start(0)
app.listen()
# app.run(host='0.0.0.0')
IOLoop.current().start()
if __name__ == '__main__':
main()
What is the mistake here and how can I fix it?
It looks like the deployment is succeeding, but when Zappa checks to see if the code is working, the return code is 502, which suggests that the lambda function is failing to run in the lambda environment.
Taking a look at the logs, the critical line is:
AttributeError: module 'main' has no attribute 'app'
And this is true, if we look at your code, at no point do you expose an attribute called app in main.py.
I'm not experienced with Tornado, but I suspect that if you move the declaration of app out of the main() function and into the root scope, then the handler should succeed.
For example:
# rest of the file...
self.finish()
app = tornado.web.Application([
(r'/', MainHandler),
], debug=True)
app.listen()
def main():
IOLoop.current().start()
if __name__ == '__main__':
main()

Using cx_freeze in PyQt5, can't find PyQt5

I want to build a standalone binary file for windowz(xp, 7, ...) from my python3(+ PyQt5) script and I inevitably use cx_freeze because other freezing apps do not work with python3 (like py2exe, pyinstaller).
I read the cx_freeze docs and lots of stackoverflow asks ans use this config for setup.py‍‍‍ file :
import sys
from cx_Freeze import setup, Executable
path_platforms = ( "C:\Python33\Lib\site-packages\PyQt5\plugins\platforms\qwindows.dll", "platforms\qwindows.dll" )
includes = ["atexit","PyQt5.QtCore","PyQt5.QtGui", "PyQt5.QtWidgets"]
includefiles = [path_platforms]
excludes = [
'_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
'Tkconstants', 'Tkinter'
]
packages = ["os"]
path = []
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
"includes": includes,
"include_files": includefiles,
"excludes": excludes,
"packages": packages,
"path": path
}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
exe = None
if sys.platform == "win32":
exe = Executable(
script="D:\\imi\\aptanaWorKPCworkspace\\azhtel\\tel.py",
initScript = None,
base="Win32GUI",
targetDir = r"dist",
targetName="tel.exe",
compress = True,
copyDependentFiles = True,
appendScriptToExe = False,
appendScriptToLibrary = False,
icon = None
)
setup(
name = "telll",
version = "0.1",
author = 'me',
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [exe]
)
run with:
python D:\imi\aptanaWorKPCworkspace\azhtel\setup.py build
This is my library that I used:
from PyQt5 import QtGui, QtCore, QtWidgets
import sys
from telGui import Ui_MainWindow
import mysql
import mysql.connector
from mysql.connector import errorcode
and this is my files in workspace:
But this error happened (or another kind of errors).
Why this happened and what config for setup.py is good for pyqt5 app ??
Thanks.
Python3.3, PyQt5, Mysqlconnector.
I solved this problem with find another directory near the dist directory called build and all library files are in there, i delete targetDir = r"dist" part of setup.py and everythings is alright !
Try pyinstaller. It's much better than cxfreeze.

Resources