I am trying to use WSGI on Windows Server to run a simple flask app. I keep running into the following error:
Error occurred while reading WSGI handler: Traceback (most recent call
last): File "c:\inetpub\wwwroot\test_site\wfastcgi.py", line 711, in
main env, handler = read_wsgi_handler(response.physical_path) File
"c:\inetpub\wwwroot\test_site\wfastcgi.py", line 568, in
read_wsgi_handler return env, get_wsgi_handler(handler_name) File
"c:\inetpub\wwwroot\test_site\wfastcgi.py", line 551, in
get_wsgi_handler raise ValueError('"%s" could not be imported' %
handler_name) ValueError: "app.app" could not be imported StdOut:
StdErr
For my site I configured a handler to call the FastCGIModule from Microsoft Web Platform installer
My app file looks as such:
from flask import Flask, request, jsonify
from analyzers import analyzer
import write_log
app = Flask(__name__)
#app.route("/")
def test():
return "Test load"
#app.route('/analyze', methods=['POST'])
def parse():
text = request.json['text']
name = request.json['name']
model = request.json['model']
try:
convert_flag = request.json['convert_flag']
except KeyError:
convert_flag = False
results= analyzer(text, name, model, convert_dose=convert_flag)
write_log.write_log(text, name, model, results)
return jsonify(results)
if __name__ == "__main__":
app.run()
If I comment out the custom import of my analyzer script and my write_log script along with the POST method things will run, so I know I must be messing something up there.
Does anybody have any suggestions?
Thanks in advance.
Paul
I had the same issue and the problem was with a third-party library. What's causing your problem is certainly something different, but here's something I did to identify my issue and may help you as well:
Open wfastcgi.py
Locate the method get_wsgi_handler (probably on line 519)
There's a try/except inside a while module_name statement
Add raise to the end of the except block and save the file, like this:
except ImportError:
...
raise
Access your website URL again and check your logs, they now should be more detailed about what caused the ImportError and will point you in the right direction to fix the issue
Related
im trying to do a instagram bot but i just could run the code once, and it worked fine but when i tried again it dropped me this error
i wont write my user and pass in this question obviously haha
from instabot import *
session = Bot()
session.login(username = "myuser",
password = "mypass")
and i get this error
2021-02-01 16:07:42,401 - INFO - Instabot version: 0.117.0 Started
Traceback (most recent call last):
File "C:/Users/EQUIPO/Desktop/5 CUATRI/Phyton/Ejercicios Prueba/nsoe.py", line 3, in <module>
session.login(username = "nota.niceplace",
File "C:\Program Files\Python38\lib\site-packages\instabot\bot\bot.py", line 443, in login
if self.api.login(**args) is False:
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api.py", line 240, in login
self.load_uuid_and_cookie(load_cookie=use_cookie, load_uuid=use_uuid)
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api.py", line 199, in load_uuid_and_cookie
return load_uuid_and_cookie(self, load_uuid=load_uuid, load_cookie=load_cookie)
File "C:\Program Files\Python38\lib\site-packages\instabot\api\api_login.py", line 354, in load_uuid_and_cookie
self.cookie_dict["urlgen"]
KeyError: 'urlgen'
You need to delete config folder which is automatically created by system when you run this code first time.
So you need to delete this folder every time before run your code.
This config folder is in same directory where your file is saved.
I had same problem and i am able to solve by this way.
This code will fix everything automatically for you just change image name and path.
from instabot import Bot
import os
import shutil
def clean_up(i):
dir = "config"
remove_me = "imgs\{}.REMOVE_ME".format(i)
# checking whether config folder exists or not
if os.path.exists(dir):
try:
# removing it so we can upload new image
shutil.rmtree(dir)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
if os.path.exists(remove_me):
src = os.path.realpath("imgs\{}".format(i))
os.rename(remove_me, src)
def upload_post(i):
bot = Bot()
bot.login(username="your_username", password="your_password")
bot.upload_photo("imgs/{}".format(i), caption="Caption for the post")
if __name__ == '__main__':
# enter name of your image bellow
image_name = "img.jpg"
clean_up(image_name)
upload_post(image_name)
As Raj said. You need to delete the config folder like this from where you ran the python script. Sorry for making a separate answer but for me it was not immediate clear where this config folder was so I thought it might help.
rm -rf config
Unfortunately the library is quite poor with their error messages
Unfortunately, it seems that instabot library's maintenance is down, don't try to run anything using that lib, won't work, and might, as commented by some users, compromise your account! sorry..
So every time I try to run the app I get "RuntimeError: generator raised StopIteration error". I am using Python 3.7 (btw I don't know how to type fancy in this so its nice to see)
I have tried changing utils.py
yield next(seq) to
try:
yield next(seq)
except StopIteration:
return
but that didn't seem to work. I've also re installed webpy but it didn't work.
import web
urls = (
'/(.*)', 'Hello'
)
app = web.application(urls, globals())
class Hello:
def GET(self, name):
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
This error pops up:
Traceback (most recent call last):
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\utils.py", line 526, in take
yield next(seq)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/Korisnik/Desktop/Python Files/Web/main.py", line 6, in
app = web.application(urls, globals())
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\application.py", line 62, in init
self.init_mapping(mapping)
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\application.py", line 130, in init_mapping
self.mapping = list(utils.group(mapping, 2))
File "C:\Users\Korisnik\Desktop\Python Files\Web\venv\lib\site-packages\web\utils.py", line 531, in group
x = list(take(seq, size))
RuntimeError: generator raised StopIteration
The webpy documentation says that the latest full release (0.39) only works on Python 2. There's work in progress towards supporting Python 3, but for now it's only available in development builds.
You can try installing one of those, with pip install web.py==0.40-dev1.
I was going into my main python folder and changing the yield thing there INSTEAD of going into the folder where my project is. The fix is changing the yield thing to the improved yield thing.
This has been vexing me for a while now. I am trying to create a very simple REST-like interface (without using third-party libraries, which I know are available).
The idea behind it is that I can have a directory, for example mylib, where I can drop in python files, like do_something.py and, by POSTing to http://localhost/do_something the code will spring into life and do something!
I think I have managed to get somewhere near to my goal with the following structure:
The contents of the files are as follows.
example.py
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
import json, logging
from mylib import my_module
class MyRequestHandler (BaseHTTPRequestHandler):
# Send JSON responses
# -----------
def send_json(self, json_message, response_code=200):
self.send_response(response_code)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.request.sendall(json.dumps(json_message).encode())
# Get JSON requests
# ----------
def get_json(self):
body = self.rfile.read(int(self.headers.get('Content-Length')))
if (body):
try:
receivedData = json.loads(body.decode())
except:
self.send_json({"Status": "Error", "Message": "Invalid JSON received"}, 400)
receivedData = None
else:
receivedData = None
return receivedData
# POST
# ---------
def do_POST(self):
module_to_call = (self.path).replace('/', '.')[1:]
if module_to_call.endswith('.'): # Remove trailing dot
module_to_call = module_to_call[:-1]
print("Path is: '" + module_to_call + "'")
# invoke function
module_to_call = getattr(self, module_to_call)
response = module_to_call()
self.send_json(response)
# GET
# --------
def do_GET(self):
pass
# -----------------------------------------------------------------------------
# Server startup code
# -------------------
def start_server():
# Begin serving
# -------------
port = 8003
server = HTTPServer(('', port), MyRequestHandler)
print(("Server now running on port {0} ...").format(port))
server.serve_forever()
# -----------------------------------------------------------------------------
# Start the Server
# ----------------
if __name__ == '__main__':
start_server()
my_module.py
def my_module():
print("Hello World!")
return{'Greeting': 'Hello World!'}
When I fire up the server and attempt to POST to http://localhost:8003/my_module, I get the following output:
Server now running on port 8003 ...
Path is: 'my_module'
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 59541)
Traceback (most recent call last):
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 313, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 341, in process_request
self.finish_request(request, client_address)
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 354, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\socketserver.py", line 681, in __init__
self.handle()
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 422, in handle
self.handle_one_request()
File "C:\Users\Test\AppData\Local\Programs\Python\Python35-32\lib\http\server.py", line 410, in handle_one_request
method()
File ".\example.py", line 43, in do_POST
module_to_call = getattr(self, module_to_call)
AttributeError: 'MyRequestHandler' object has no attribute 'my_module'
----------------------------------------
This makes perfect sense, since 'MyRequestHandler" does not have an attribute "my_module"! What I can't wrap my head around, is how to fix this?
Should I pass "mylib" into MyRequestHandler? Should I perform the import within the class (but then the functionality would only be available within the class)?
I'm trying to keep things clean and simple, so that even a Python novice (like I seem to be!) can just write a standalone script, drop it into "mylib" and everything "just works". The novice could visit the web address of their script and have it magically run.
Any help or advice would be gratefully received.
Use the __import__() method:
temp = __import__('mylib', globals(), locals(), ['module_to_call'], -1)
response = temp.module_to_call()
I use 2.6 at work, and this is usually used by those using even 2.7 because the importlib module is far more robust in 3. If you are using 3 you can do the following:
from importlib import import_module
temp = import_module('mylib')
but now you have to use getattr to get the function you want to be called
func_to_call = getattr(temp, 'module_to_call')
response = func()
Or you can have a dictionary of functions in another module, but that will require a lot of work as that dictionary grows.
I'm trying to use CherryPy's WSGI server to serve static files, like in Using Flask with CherryPy to serve static files. Option 2 of the accepted answer there looks exactly like what I'd like to do, but I'm getting a KeyError when I try to use the static directory handler.
What I've tried:
>>>> import cherrypy
>>>> from cherrypy import wsgiserver
>>>> import os
>>>> static_handler = cherrypy.tools.staticdir.handler(section='/', dir=os.path.abspath('server_files')
>>>> d = wsgiserver.WSGIPathInfoDispatcher({'/': static_handler})
>>>> server = wsgiserver.CherryPyWSGIServer(('localhost', 12345), d)
>>>> server.start()
Then, when I try to access the server I'm getting a 500 response and the following error in the console:
KeyError('tools',)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1353, in communicate
req.respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 868, in respond
self.server.gateway(self).respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2267, in respond
response = self.req.server.wsgi_app(self.env, self.start_response)
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2477, in __call__
return app(environ, start_response)
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 175, in handle_func
handled = self.callable(*args, **self._merged_args(kwargs))
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 102, in _merged_args
tm = cherrypy.serving.request.toolmaps[self.namespace]
KeyError: 'tools'
This is displayed twice for each time I try to hit anything that the server should be able to display. When I hooked up a Flask app to the server the Flask app worked as expected, but the static file serving still gave the same error.
What do I need to do to get the staticdir.handler to work?
I've tried various ways of getting this to work and up until today was also hitting the KeyError you have been seeing (among other issues).
I finally managed to get CherryPy to serve static alongside a Django app by adapting the code from this gist (included below).
import os
import cherrypy
from cherrypy import wsgiserver
from my_wsgi_app import wsgi
PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'public'))
class Root(object):
pass
def make_static_config(static_dir_name):
"""
All custom static configurations are set here, since most are common, it
makes sense to generate them just once.
"""
static_path = os.path.join('/', static_dir_name)
path = os.path.join(PATH, static_dir_name)
configuration = {static_path: {
'tools.staticdir.on': True,
'tools.staticdir.dir': path}
}
print configuration
return cherrypy.tree.mount(Root(), '/', config=configuration)
# Assuming your app has media on diferent paths, like 'c', 'i' and 'j'
application = wsgiserver.WSGIPathInfoDispatcher({
'/': wsgi.application,
'/c': make_static_config('c'),
'/j': make_static_config('j'),
'/i': make_static_config('i')})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8070), application,
server_name='www.cherrypy.example')
try:
server.start()
except KeyboardInterrupt:
print "Terminating server..."
server.stop()
Hopefully wrapping a Flask app will be fairly similar.
The key for me was using the cherrypy.tree.mount on a dummy class, rather than trying to use the staticdir.handler directly.
For the curious - I used the code in the gist to customise a version of django-cherrypy's runcpserver management command, although in hindsight it would probably have been easier to create a new command from scratch.
Good luck (and thanks to Alfredo Deza)!
I'm trying to get a simple python script from the learnpythonthehardway tutorial to show up on my browser but keep encountering getting the following error:
$ python app.py
http://0.0.0.0:8080/
Traceback (most recent call last):
File "app.py", line 15, in <module>
app.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/application.py", line 310, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/httpserver.py", line 148, in runsimple
server.start()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/web/wsgiserver/__init__.py", line 1753, in start
raise socket.error(msg)
socket.error: No socket could be created
The script app.py is this:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == "__main__":
app.run()
What should I try now? It actually worked to print Hello World on my browser once, but I've been meddling with it and now it's giving me error messages regardless of what I try. I don't know what these messages mean or how to fix them.
The problem is due to the way web.py loading works, you need to have the creation and running of the app only occur if this is the main entry point of the program.
Otherwise, the class loader in web.py will reload this file again later, and wind up spawning a new server when its intent was simply to load a class.
try this
if __name__ == '__main__' :
app = web.application(urls, globals())
app.run()
Source: No socket could be created (other causes)
Changing the port address could fix this. Probably 8080 might be used for something else. Idk im speculating. The following fixed the issue for me.
try
$ python app.py 8081