project interpreter and local env IMAGEI'm having a real problem with using the module flask , I've tried a lot of the solutions here on the forum but none has worked.
I can see flask is installed
pip list - showing flask
in the setting the module flask is installed in project interpreter
when I type the code I can see the module comes up
However when I launch the code I get an error
No module named 'flask'
I've tried to re-install pycharm
I've tried to uninstall and install flask again
still the same problem. Any advice ?
The file name vsearch.py
Here is the code:
from flask import Flask, render_template, request, escape
app = Flask(__name__)
def search4words(phrase: str, letters: str) -> set:
return set(letters).intersection(set(phrase))
def log_request(req: 'flask_request', res: str) -> None:
with open('vsearch.log', 'a') as log:
print(req.form, req.remote_addr, req.user_agent, res, file=log,
sep='|')
#app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4words(phrase, letters))
log_request(request, results)
return render_template('results.html', the_phrase=phrase,
the_letters=letters, the_title=title,
the_results=results,)
#app.route('/')
#app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome back
AGAIN!!!!!')
#app.route('/viewlog')
def view_the_log() -> 'html':
contents = []
with open('vsearch.log') as log:
for line in log:
contents.append([])
for item in line.split('|'):
contents[-1].append(escape(item))
titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results')
return render_template('viewlog.html',
the_title = 'View log',
the_row_titles = titles,
the_data = contents,)
if __name__ == '__main__' :
app.run(debug=True)
Your issue was attempting to run vsearch.py through terminal, rather than through PyCharm's interpreter (which was correctly installed). In order to utilize the virtual environment, you should configure it to be used correctly when running your code.
There are multiple ways of activating your virtual environment, so please find that which is applicable to your project. A good source for this would be https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/.
Related
I'm currently following the head-first book on python. Briefly, I am trying to run a python file that imports a module and when I run it I get an error saying ModuleNotFoundError: No module named 'vsearch'
This is the folder structure:
New Folder
hello_flask.py
mymodules.py
dist
vsearch.egg-info
readme.txt
setup.py
vsearch.py
The following is the code for the relevant (I think):
hello_flask.py
from flask import Flask
from vsearch import search4letters
app = Flask(__name__)
#app.route('/')
def hello() -> str:
return 'Hello world from Flask!'
#app.route('/search4')
def do_search()-> str:
return str(search4letters('life,the universe, and everything', 'eiru!'))
app.run()
vsearch.py
def search4vowels(phrase: str) -> set:
"""Return any vowels found in a supplied phrase."""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search4letters(phrase:str, letters:str = 'aeiou') ->set:
"""Return a set of the 'letters' found in 'phrase'."""
return set(letters).intersection(set(phrase))
setup.py
from setuptools import setup
setup(
name = 'vsearch',
vesion = '1.0',
description = 'The Head First Python Search Tools',
author = 'HF Python 2e',
author_email = 'hfpy2e#gmail.com',
url='headfirstlabs.com',
py_modules = ['vsearch'],
)
So the book tells me to run hello_flask.py in windows powershell using py -3 hello_flask.py but when I run it I get the following error:
Traceback (most recent call last):
File "C:\Users\Juan\Desktop\New folder\hello_flask.py", line 2, in <module>
from vsearch import search4letters
ModuleNotFoundError: No module named 'vsearch'
I have created the distribution file per the book and have searched among the internet as best as I could and I haven't been able to fix it. I have a feeling it would have to be something with the pathway, but I'm not sure. I also tried pip installing vsearch from the powershell which was successful but did not fix my problem. Just in case, the pip install for vsearch installed on c:\users\juan\appdata\local\programs\python\python310\lib\site-packages (1.1.0).
I found a fix! Credits to another page but I had to change the import statement for vsearch on hello_flask.py to import mymodules.vsearch import search4letters
I installed Django on Windows 10, Django Version 3, Python 3.8 from Conda, with env, on VS Code
My Django works fine without any problem and my App and Project also works fine, but I decided to use Faker to generate some fake data in my DB, I have to mention that my Model works and connected successfully to my DB and migration process was successful without any problem.
I write this Standalone app for Faker to run it whenever I need manually:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
# Implement Fake Population script here.
import random
from first_app.models import AccessRecord, Topic, Webpage
from faker import Faker
fakegen = Faker()
topics = ['Search', 'Social', 'Marketplace', 'News', 'Games']
def add_topic():
t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t
def populate(N=5):
for entry in range (N):
# Get the topic for the entry
top = add_topic()
# Create the fake data for that entry
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
# Create the new webpage entry
webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0]
# Create a fake access record for that webpage
acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == "__main__":
print('Population Script!')
populate(20)
print('Population Completed!')
But whenever I run this code, I get this error:
> (myDjangoEnv) C:\my_path\first-project
> C:/Users/HPTav/anaconda3/python.exe
> c:/my_path/first_project/populate_first_app.py
Traceback (most recent call last):
File "c:/my_path/first_project/populate_first_app.py", line 4, in
<module>
import django
ModuleNotFoundError: No module named 'django'
> (myDjangoEnv) C:\my_path\first-project>
I replaced the path with my_path to make it easier for you when you read the console error.
This is my Django project structure:
I am sure I have Django, as I said my Django app and project works fine.
I checked it by this way to make sure I have Django on this folder:
This project is available in GitHub:
https://github.com/hptavakoli/django_first_app
Sounds like you don't have django installed, install it using this command:
pip install django
In your Command prompt.
Visit this site for additional info: Installing django using pip
What you can do is this:
"Add 'python' while calling populate_first_app.py in the terminal."
python populate_first_app.py
I'm using Bottle for a Python project and I've set the project to run on the localhost:8080 (Windows 10 laptop). I’ve coded the project on VS Code, however, when I start the debugger on VS Code’s integrated terminal,I am presented with Error 500 on my browser (Google Chrome).
The project worked fine on a TA's machine, however on my laptop, bottle isn't routing to the index page, even when I explicitly had it import it from the static_file and adding the root file to the ‘run’ function. I tried running the example from Bottlepy.org, and even that isn’t working.
The only thing that has worked was:
from bottle import run, route
#route('/')
def hello():
return "If you're seeing this message, then bottle is working"
run(host='localhost', port=8080)
Again, I’ve ran:
from bottle import run, route, template
#route('/')
def hello():
return template("index.html")
run(host='localhost', port=8080)
and
from bottle import run, route, static_file
#route('/static/')
def hello():
return static_file('index.html', root='static')
run(host='localhost', port=8080)
Including the example from bottlepy.org, to which resulted in:
Error 500 Template 'index.html' not found.
Or
Error 500 ‘Template ‘/’ not found
I don’t believe it’s a PATH issue with Python, but it could be a JSON file issue with VS code. All the Python packages on my machine are updated and I’m out of ideas at the moment. Your suggestions/recommendations would be appreciated. Thank you.
Probably the issue is because the integrated shell executes the code in some other directory where the file 'index.html' is.
To help solve the issue, replace the file name with an absolute path, e.g.
#route('/static/')
def hello():
return static_file(os.path.join(os.path.dirname(__file__), 'index.html'), root='static')
I've worked through installing Python as a CGI application on IIS on Windows 7. This is pretty straightforward, but I'd like to use the WSGI stuff, for better flexibility.
I downloaded the archive for isapi_wsgi, unzipped it, and then ran the install as per the instructions, like this:
\python27\python.exe setup.py install
This succeeded:
Then I coded a .py module that had the wsgi glue in it, and tried installing it. This failed like so:
It's a COM Moniker error, and I know that the IIS6-compatible management stuff is based on COM Monikers, which reminded me that there is a pre-req for isapi_wsgi of the IIS6-compatible management stuff. I ran \windows\system32\OptionalFeatures.exe and installed that, then re-ran the .py module and it installed correctly.
C:\dev\wsgi>\Python27\python.exe app1_wsgi.py
Configured Virtual Directory: /wsgi
Installation complete.
Ok, wonderful. Now when I look in the current directory, I see a new DLL named _app1_wsgi.dll, and when I look in IIS Manager I can see a new IIS vdir, and a scriptmap within that vdir for '*', which is mapped to the _app1_wsgi.DLL. All good. But! making a request to http://localhost/wsgi gives me a 500 error.
Through some trial-and-error I see that the .py module that defines my handlers must be in the site-packages directory. I am very surprised by this.
Can I avoid this? Can I simply put the .py module in the same directory as the generated .dll file? Or do I need to deploy all of my python logic to site-packages in order to run it from the WSGI mechanism?
The answer is:
the installation of isapi_wsgi as described in the question, is correct.
with the basic boilerplate of app.py as shown in the example code accompanying isapi_wsgi, the python classes for the web app need to be in the site-packages directory.
it is possible to allow the python source modules to reside in the same directory as with the generated *.dll file, but it requires some special handling in the *wsgi.py file.
a better way to run python on Windows for development purposes is to simply download the Google App Engine and use the builtin dedicated http server. The framework that comes with the GAE SDK handles reloading and allows the .py modules to be placed in particular directories.
If you don't want to download and install the GAE SDK, then you might try the following. Using this code, when a request arrives on isapi_wsgi, the handler looks in the home directory for a py module, and loads it. If the module is already loaded, it checks the file "last modified time" and reloads the module if the last mod time is later than the time from the prior load. It works for simplistic cases but I suppose it will be brittle when there are nested module dependencies.
import sys
import os
import win32file
from win32con import *
# dictionary of [mtime, module] tuple; uses file path as key
loadedPages = {}
def request_handler(env, start_response):
'''Demo app from wsgiref'''
cr = lambda s='': s + '\n'
if hasattr(sys, "isapidllhandle"):
h = None
# get the path of the ISAPI Extension DLL
hDll = getattr(sys, "isapidllhandle", None)
import win32api
dllName = win32api.GetModuleFileName(hDll)
p1 = repr(dllName).split('?\\\\')
p2 = p1[1].split('\\\\')
sep = '\\'
homedir = sep.join(p2[:-1])
# the name of the Python module is in the PATH_INFO
moduleToImport = env['PATH_INFO'].split('/')[1]
pyFile = homedir + sep + moduleToImport + '.py'
fd = None
try:
fd = win32file.CreateFile(pyFile, GENERIC_READ, FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
except Exception as exc1:
fd = None
if fd is not None:
# file exists, get mtime
fd.close()
mt = os.path.getmtime(pyFile)
else:
mt = None
if mt is not None:
h = None
if not pyFile in loadedPages:
# need a new import
if homedir not in sys.path:
sys.path.insert(0, homedir)
h = __import__(moduleToImport, globals(), locals(), [])
# remember
loadedPages[pyFile] = [mt, h]
else:
# retrieve handle to module
h = loadedPages[pyFile][1]
if mt != loadedPages[pyFile][0]:
# need to reload the page
reload(h)
loadedPages[pyFile][0] = mt
if h is not None:
if 'handler' in h.__dict__:
for x in h.handler(env, start_response):
yield x
else:
start_response("400 Bad Request", [('Content-Type', 'text/html')])
else:
start_response("404 Not Found", [('Content-Type', 'text/html')])
yield cr()
yield cr("<html><head><title>Module not found</title>" \
"</head><body>")
yield cr("<h3>404 Not Found</h3>")
yield cr("<h3>No handle</h3></body></html>")
else:
start_response("404 Not Found", [('Content-Type', 'text/html')])
yield cr()
yield cr("<html><head><title>Module not found</title>" \
"</head><body>")
yield cr("<h3>404 Not Found</h3>")
yield cr("<h3>That module (" + moduleToImport + ") was not found.</h3></body></html>")
else:
start_response("500 Internal Server Error", [('Content-Type', 'text/html')])
yield cr()
yield cr("<html><head><title>Server Error</title>" \
"</head><body><h1>Server Error - No ISAPI Found</h1></body></html>")
# def test(environ, start_response):
# '''Simple app as per PEP 333'''
# status = '200 OK'
# start_response(status, [('Content-type', 'text/plain')])
# return ['Hello world from isapi!']
import isapi_wsgi
# The entry point(s) for the ISAPI extension.
def __ExtensionFactory__():
return isapi_wsgi.ISAPISimpleHandler(request_handler)
def PostInstall(params, options):
print "The Extension has been installed"
# Handler for our custom 'status' argument.
def status_handler(options, log, arg):
"Query the status of the ISAPI?"
print "Everything seems to be fine..."
if __name__=='__main__':
# This logic gets invoked when the script is run from the command-line.
# In that case, it installs this module as an ISAPI.
#
# The API provided by isapi_wsgi for this is a bit confusing. There
# is an ISAPIParameters object. Within that object there is a
# VirtualDirs property, which itself is a list of
# VirtualDirParameters objects, one per vdir. Each vdir has a set
# of scriptmaps, usually this set of script maps will be a wildcard
# (*) so that all URLs in the vdir will be served through the ISAPI.
#
# To configure a single vdir to serve Python scripts through an
# ISAPI, create a scriptmap, and stuff it into the
# VirtualDirParameters object. Specify the vdir path and other
# things in the VirtualDirParameters object. Stuff that vdp object
# into a sequence and set it into the ISAPIParameters thing, then
# call the vaguely named "HandleCommandLine" function, passing that
# ISAPIParameters thing.
#
# Clear as mud?
#
# Seriously, this thing could be so much simpler, if it had
# reasonable defaults and a reasonable model, but I guess it will
# work as is.
from isapi.install import *
# Setup the virtual directories -
# To serve from root, set Name="/"
sm = [ ScriptMapParams(Extension="*", Flags=0) ]
vdp = VirtualDirParameters(Name="wsgi", # name of vdir/IIS app
Description = "ISAPI-WSGI Demo",
ScriptMaps = sm,
ScriptMapUpdate = "replace"
)
params = ISAPIParameters(PostInstall = PostInstall)
params.VirtualDirs = [vdp]
cah = {"status": status_handler}
# from isapi.install, part of pywin32
HandleCommandLine(params, custom_arg_handlers = cah)
Using this model, requesting http://foo/wsgi/bar will try loading bar.py from the home directory with the WSGI .dll file. If bar.py cannot be found, you get a 404. If bar.py has been updated since the last run, it reloads. If bar cannot be loaded, you get a 500.
bar.py must export a method called handler, publicly. That method must be a generator. like so:
import time
def handler(env, start_response):
start_response("200 OK", [('Content-Type', 'text/html')])
cr = lambda s='': s + '\n'
yield cr("<html><head><title>Hello world!</title></head><body>")
yield cr("<h1>Bargle Bargle Bargle</h1>")
yield cr("<p>From the handler...</p>")
yield cr("<p>(bargle)</p>")
yield cr("<p>The time is now: " + time.asctime() + " </p>")
yield cr("</body></html>")
__all__ = ['handler']
But as I said, I think GAE is probably a better way to develop Python webapps using Windows.
put this on top of your scrip:
import site
site.addsitedir('path/to/your/site-packages')
the same problem you had, was solved with this two lines
I have the following python script which runs perfectly if run separately:
import arcpy
val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
print str(val)
I want to expose this as a web service and so I installed web.py and wrote the following code for code.py. but it gives errors(when invoked. compiles fine).
import web
import arcpy
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
return str(val)
if __name__ == "__main__":
app.run()
When i invoke this using http://localhost:8080, i get the following error:
<class 'arcgisscripting.ExecuteError'> at /
ERROR 000582: Error occurred during execution.
Python C:\Program Files (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\management.py in GetCellValue, line 8460
Web GET http://localhost:8080/
Traceback (innermost first)
C:\Program Files (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\management.py in GetCellValue
be returned."""
try:
retval = convertArcObjectToPythonObject(gp.GetCellValue_management(*gp_fixargs((in_raster, location_point, band_index), True)))
return retval
except Exception, e:
raise e ...
#gptooldoc('GetRasterProperties_management', None)
def GetRasterProperties(in_raster=None, property_type=None):
"""GetRasterProperties_management(in_raster, {property_type})
Returns the properties of a raster dataset.
I have tried Debugging it in many ways, the code .py runs fine if i just return a "hello". The library i am using is a ArcGIS Geoprocessing toolbox library.
Any ideas as to what might be wrong?
That looks like an error from the third party module. Try finding out what that error code (000582) actually means to the application.