Im trying to run my Python app but I am getting the following error message:
File "services/user.py", line 1, in <module>
2020-12-01 15:28:34 -0800 [web][cinema-app-web-3-6774f77795-k5mqz]: from services import root_dir, nice_json
2020-12-01 15:28:34 -0800 [web][cinema-app-web-3-6774f77795-k5mqz]: ImportError: cannot import name root_dir
This is the folder structure I have today:
cinema-app
setup.py
requirements.txt
database
bookings.json
movies.json
showtimes.json
users.json
services
__init__.py
bookings.py
movies.py
showtimes.py
user.py
I then run the app by using:
python services/user.py
but then I get the error message above.
Here is the content of my __init__.py:
import os
import json
from flask import make_response
def root_dir():
""" Returns root director for this project """
return os.path.dirname(os.path.realpath(__file__ + '/..'))
def nice_json(arg):
response = make_response(json.dumps(arg, sort_keys = True, indent=4))
response.headers['Content-type'] = "application/json"
return response
Here is the user.py file content:
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound, ServiceUnavailable
import json
import requests
app = Flask(__name__)
with open("{}/database/users.json".format(root_dir()), "r") as f:
users = json.load(f)
#app.route("/", methods=['GET'])
def hello():
return nice_json({
"uri": "/",
"subresource_uris": {
"users": "/users",
"user": "/users/<username>",
"bookings": "/users/<username>/bookings",
"suggested": "/users/<username>/suggested"
}
})
#app.route("/users/<username>/suggested", methods=['GET'])
def user_suggested(username):
"""
Returns movie suggestions. The algorithm returns a list of 3 top ranked
movies that the user has not yet booked.
:param username:
:return: Suggested movies
"""
raise NotImplementedError()
if __name__ == "__main__":
app.run(port=5000, debug=True)
Any help would be much appreciated
If you want to make a package, your code is right. To simplify, I rewrite the __init__.py and user.py:
user.py:
from services import root_dir, nice_json
def main():
print(root_dir)
print(nice_json)
if __name__ == '__main__':
main()
__init__.py:
def root_dir():
pass
def nice_json():
pass
And you can run in terminal this way:
user#computer$ python -m services/user
<function root_dir at 0x7fd1d0083670>
<function nice_json at 0x7fd1d0083700>
Here dont use the 'py' extension, the '-m' options tells python this is a modular import. You can still import your package from python:
user#computer$ python
Python 2.7.18 (default, Aug 4 2020, 11:16:42)
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from services import user
>>> user.main()
<function root_dir at 0x7fa2e21a2dd0>
<function nice_json at 0x7fa2e21b01d0>
Code this way you can use your package when it is in PATH or in site-packages python dir.
Related
I am working on a project in FastAPI, there is a problem in importing packages. My project structure is like this.
My main.py file is this:
from fastapi import FastAPI
import uvicorn
import asyncio
#imports
from .routers import fileupload
from .startup import startup_function
app = FastAPI()
#app.on_event("startup")
def on_start_up():
startup_function()
#fileupload router
app.include_router(fileupload.router)
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=5000, reload=True)
and my fileupload.py file is like this:
from fastapi import APIRouter, HTTPException
import asyncio
from ..posts.utils import get_file_upload, pipeline
from ..posts.schemas import FileUpload
from ..startup import db
router = APIRouter()
#router.post("/fileupload")
async def file_upload(file_upload: FileUpload):
print("in file upload")
# return {"message": "File uploaded successfully"}
# Convert the base64-encoded audio data to a WAV file
asyncio.create_task(get_file_upload(file_upload))
asyncio.create_task(pipeline(file_upload))
result = await db.insert_one(file_upload.dict(exclude={"Datei"}))
if not result.acknowledged:
raise HTTPException(status_code=500, detail="Failed to upload file")
#return aa response asynchronously
if result.acknowledged:
return {"message": "File uploaded successfully"}
else:
#return failed message with error code and details
return {"message": "Failed to upload file"}
It is giving me errors on every import, I couldn't understand from the documentation, I have tried different ways, removing . from the imports, but it does not work. Any help would be appreciated. Thanks.
Traceback (most recent call last):
File "/home/Fast-api/src/main.py", line 9, in <module>
from .routers import fileupload
ImportError: attempted relative import with no known parent package
This is the error to start with, I don't know how to resolve this error
I use Python eventlet pool and requests module to speed up my HTTPS request.
But it makes the requests process slower, I try to find the answer to the question these days.
I find some use cases for Python eventlet. such as Speed of fetching web pages with Eventlet and Python? and https://eventlet.net/doc/ these documents mentioned.
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
urls = [
"http://www.google.com/intl/en_ALL/images/logo.gif",
"http://python.org/images/python-logo.gif",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif",
]
import eventlet
from eventlet.green.urllib.request import urlopen
def fetch(url):
return urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print("got body", len(body))
I notice only Python module urllib and urllib2 are used in these examples, and I can not import urllib3 from event.green module.
Python 2.7.5 (default, Nov 16 2020, 22:23:17)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from eventlet.green import urllib3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name urllib3
>>>
When I check the Python requests module, I find it uses urllib3 module.
[root#ci-4183549-pzhang requests]# ls
adapters.py api.py auth.py certs.py compat.py cookies.py exceptions.py hooks.py __init__.py models.py packages sessions.pyo status_codes.pyo structures.pyo utils.pyo
adapters.pyc api.pyc auth.pyc certs.pyc compat.pyc cookies.pyc exceptions.pyc hooks.pyc __init__.pyc models.pyc sessions.py status_codes.py structures.py utils.py
adapters.pyo api.pyo auth.pyo certs.pyo compat.pyo cookies.pyo exceptions.pyo hooks.pyo __init__.pyo models.pyo sessions.pyc status_codes.pyc structures.pyc utils.pyc
[root#ci-4183549-pzhang requests]# ls packages/
chardet __init__.py __init__.pyc __init__.pyo urllib3
The question is:
Does it mean the requests module can not be eventlet monkeypatched, even if I do eventlet.monkey_patch() at the beginning of my script? it will not work correctly, will it?
Any help or hint is appreciated.
I have a VPS Hosting in cPanel, and a Flask-App.
I followed the instructions of How to install WSGI Application in cPanel.
Everything is working fine, when I run the application using the terminal, but when I open the App URL, it shows the following error:
Traceback (most recent call last):
File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module>
app_module = load_app()
File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app
return imp.load_source('passenger_wsgi', startup_file)
File "/home/qsemh/Maidan/passenger_wsgi.py", line 8, in <module>
wsgi = imp.load_source('wsgi', 'wsgi.py')
File "wsgi.py", line 1, in <module>
from flaskr import create_app
File "/home/qsemh/Maidan/flaskr/__init__.py", line 133
print(f"Validate {len(users)} Users At {current_time}")
^
SyntaxError: invalid syntax
So I've decided to create a simpler app in order to detect the issue, the app is as following :
passenger_wsgi.py
#!/usr/bin/env python3
import sys
from flask import Flask
application = Flask(__name__)
application.route("/")
def index():
return sys.version
When I run this simple Application Using the URL it shows the following as a respond :
2.7.5 (default, Apr 2 2020, 13:16:51) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
even though I've used the shebang #!/usr/bin/env python3 at the start of the file, and when I run it using the terminal, it works as if it using python3.
I've tried changing the shebang to the following formats :
#!/usr/bin/python3
#!/usr/bin/env 'python3'
but they gave the same result.
What is the problem here, and How can I solve it?
I've found the Correct approach to solve this issue;
Basically, I only needed to add the following lines at the beginning of my passenger_wsgi.py file :
import os
INTERP = "/usr/bin/python3"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
so the final result would be :
passenger_wsgi.py
#!/usr/bin/env python3
import sys
import os
# Solution
INTERP = "/usr/bin/python3"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
from flask import Flask
application = Flask(__name__)
application.route("/")
def index():
return sys.version
and the respond is correctly as I intended in the first place:
3.6.8 (default, Apr 2 2020, 13:34:55) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
This answer might be for some cPanel users. My cPanel is using passenger and wsgi, and even though my cPanel Python application is set to use python 3.9. it was running 2.7.5. Worse, it set all the 2.7 folders in the path.
So I ended up with this helper script called from
passenger_wsgi.py. I'm moved all the code out of this file into an import because this file may get blown away and re-created in some cases. It's not safe to rely on code in this file surviving. It's an auto generated file.
Put set_python_environment.py file in the same directory as passenger_wsgi.py
set_python_environment.py
# -*- coding: UTF-8 -*-
# insert these lines into passenger_wsgi.py if that file is rebuilt:
# import set_python_environment
# set_python_environment.upgrade_python()
import sys
import os
def upgrade_python():
try:
python_interpreter = "/home/username/virtualenv/YourApplicationPath/3.9/bin/python3.9_bin"
if sys.executable != python_interpreter:
print('switching from ' + sys.version + ' to ' + python_interpreter + '...')
print('directory: ' + os.path.dirname(__file__))
print('file: ' + __file__)
print('arg 0: ' + sys.argv[0])
# rebuild the env path variable
print('old system path:\n' + "\n".join(str(x) for x in sys.path))
print('\n')
for x in sys.path:
sys.path.remove(x)
sys.path.append('/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts')
# App 3956 output: /usr/lib/python2.7/site-packages/pyzor-1.0.0-py2.7.egg
# App 3956 output: /usr/lib64/python27.zip
# App 3956 output: /usr/lib64/python2.7
sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib64/python3.9')
# App 3956 output: /usr/lib64/python2.7/plat-linux2
# App 3956 output: /usr/lib64/python2.7/lib-tk
# App 3956 output: /usr/lib64/python2.7/lib-old
# App 3956 output: /usr/lib64/python2.7/lib-dynload
# App 3956 output: /home/username/.local/lib/python2.7/site-packages
# App 3956 output: /usr/lib64/python2.7/site-packages
sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib64/python3.9/site-packages')
# App 3956 output: /usr/lib64/python2.7/site-packages/gtk-2.0
# App 3956 output: /usr/lib/python2.7/site-packages
sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib/python3.9/site-packages')
sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/bin')
print('new system path:\n' + "\n".join(str(x) for x in sys.path))
print('\n')
os.execl(python_interpreter, python_interpreter, *sys.argv)
else:
print('...continuing with ' + sys.executable)
except Exception as e:
print(str(e))
Modified passenger_wsgi.py
# -*- coding: UTF-8 -*-
import sys
import os
import imp
import set_python_environment
set_python_environment.upgrade_python()
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')
application = wsgi.app
In order to get the right path, I typed whereis python in the ssh environment after running the source command given on the python application page, to find the location of all the python versions, and the one ending in bin turned out to be the one which actually works.
I am having below lambda function which uses Chalice.
from chalice import Chalice
from chalicelib import lookup_helper
import os
try:
from urllib import unquote
except ImportError:
from urllib.parse import unquote
app = Chalice(app_name='some_app')
#app.route('/some_route', methods=['GET'])
def some_func(arg):
//some code
When I test this function I get below error
{"errorMessage": "Unable to import module 'app': No module named 'app'", "errorType": "Runtime.ImportModuleError"}
Tue Sep 22 11:59:10 UTC 2020 : Lambda execution failed with status 200 due to customer function error: Unable to import module 'app': No module named 'app'.
Can anyone please help me out here.
Python - 3.7
Update--
from chalice import Chalice
import os
app = Chalice(app_name='some_app')
#app.route('/some_route', methods=['GET'])
def some_func(arg):
return {}
Reduced the function to above. Still same error.
When I checked the pipeline (azure devops), I see below error in the logs, though the step passes as a whole.
FileExistsError: [Errno 17] File exists: 'build/lambda/requests'
requirement.txt
requests==2.22.0
see https://chalice-workshop.readthedocs.io/en/latest/media-query/00-intro-chalice.html
Add a new function hello_world decorated by app.lambda_function() that
returns {"hello": "world"}. Your app.py file should now consist of the
following lines:
from chalice import Chalice
app = Chalice(app_name='workshop-intro')
#app.lambda_function()
def hello_world(event, context):
return {'hello': 'world'}
What is the name of you python file. Is it 'app.py' ?
I am trying to run dripls and when I install everything including fabric, apache2 and setup appropriate configuration files
I have the following problem
AttributeError: 'module' object has no attribute 'url'
its from the package cherrypy
On this line
app = {
'root_url': cherrypy.url()
}
Could anyone point out what might be the problem?
**Update: **
Problematic script (full)
import cherrypy
import urlparse
import uuid
import os
# Service
socket = '0.0.0.0'
dripls_main_site_port = 8080
thread_pool = 10
bin_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))), "bin")
pidfile = os.path.join(bin_path, "dripls.pid")
error_log = os.path.join(bin_path, "error_log.log")
access_log = os.path.join(bin_path, "access_log.log")
app = {
'root_url': cherrypy.url()
}
# Shaper path
shaper_path = os.path.join(bin_path, "set_ts_lo.sh")
# Shape port range
shape_start_port = 10000
shape_end_port = 11000
# Environment overrides
if os.path.exists(os.path.join(os.path.dirname(os.path.realpath(__file__)), "env.py")):
from env import *
else:
from local import *
port = int(dripls_main_site_port)
# Final url rewrite. Hack to battle the fact that cherrypy is behind a proxy on different port
def get_final_url(path, args):
cherrypy_url = cherrypy.url(path, args)
scheme, netloc, path, qs, anchor = urlparse.urlsplit(cherrypy_url)
return urlparse.urlunsplit( (scheme, urlparse.urlsplit(app['root_url'])[1], path, qs, anchor))
def get_seeded_cid(cid):
return "{0}_{1}".format(cid, uuid.uuid4().hex)"
Update :
Python 2.7.3 (default, Apr 10 2013, 05:46:21)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cherrypy
>>> cherrypy.url
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'url'
>>> print cherrypy.__file__
/usr/lib/pymodules/python2.7/cherrypy/__init__.pyc
>>>
That should work:
>>> import cherrypy
>>> cherrypy.url
<function url at 0xb6d8f80c>
Make sure that you didn't named the script cherrypy.py. If you did, it will prevent importing of cherrypy package.
Rename the file, and make sure there's no cherrypy.pyc file remained.
Sorry but I found out the problem.
It did not work if you install cherrypy using
sudo apt-get install python-cherrypy
You have install pip using
sudo apt-get install python-pip
and then
sudo pip install CherryPy