AttributeError: module 'wsgi' has no attribute 'application' - python

app.py file code:
import webbrowser
import time
#!/usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import certifi
import json
def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and return the object.
Parameters
----------
url : str
Returns
-------
dict
"""
response = urlopen(url, cafile=certifi.where())
data = response.read().decode("utf-8")
return json.loads(data)
url = ("https://financialmodelingprep.com/api/v3/quote/AAPL,FB?apikey=d099f1f81bf9a62d0f16b90c3dc3f718")
print(get_jsonparsed_data(url))
country = get_jsonparsed_data(url)
count = 0
for result in country:
if count == 0:
header = result.keys()
for head in header:
html_content = f"<div> {head} </div>"
count += 1
with open("index.html", "w") as html_file:
html_file.write(html_content)
print("Html file created successfully !!")
time.sleep(2)
webbrowser.open_new_tab("index.html")
passenger_wsgi.py file code:
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')
application = wsgi.application
Error:
Traceback (most recent call last):
File "/home/stockpee/staging/passenger_wsgi.py", line 9, in <module>
application = wsgi.application
AttributeError: module 'wsgi' has no attribute 'application'
Traceback (most recent call last):
File "/home/stockpee/staging/passenger_wsgi.py", line 9, in <module>
application = wsgi.application
AttributeError: module 'wsgi' has no attribute 'application'
Hi,
Everyone, I am new in Python. I have develop a basic application on my local machine. But when I deployed it on A2Host hosting server. I am facing above error when I run my application in web browser.
Is anyone help me to fix above issue. I will be very thankful for that person.

I will applogize in advance for my brief answer. But it has to do with the fact that you have not established a whisky app.
You need to make sure in your main application file app.py you establish your application.
def app(environ, start_response):
pprint("whoo hooo. ")
I hope this helps.

Related

In Python got many issues with Spyne

Well, here's my Python code:
#!/usr/bin/env python
from spyne import Application, rpc, ServiceBase, Unicode
from lxml import etree
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
# Wsgi это Web server Getewap Interface - стандар взаимодействия с питон программой и серверо где он работает
class Soap(ServiceBase):
#rpc(Unicode, _return=Unicode)
def Insoap(ctx, words):
print("Connection detected: ", etree.tostring(ctx.in_document))
ww = str(words).capitalize()
return ww
app = Application([Soap], tns='Capitalize', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
application = WsgiApplication(app) # Важна названия переменной, иначе сервер не поймет
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8002, application)
server.serve_forever()
But get this error, what's the problem? What should I do for a solution? Please, get help me to solve this problem
Traceback (most recent call last):
File "C:/Users/David374/PycharmProjects/untitled8/venv/test.py", line 3, in <module>
from spyne import Application, rpc, ServiceBase, Iterable, UnsignedInteger, \
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\__init__.py", line 63, in <module>
from spyne.server import ServerBase, NullServer
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\__init__.py", line 23, in <module>
from spyne.server.null import NullServer
File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\null.py", line 69
self.service = _FunctionProxy(self, self.app, async=False)
^
SyntaxError: invalid syntax
async is a reserved keyword in Python 3.7+, and you'll need to use the latest version of Spyne, which doesn't use that reserved keyword as a parameter in its functions, if you want to use it with Python 3.7+.
Either update Spyne to spyne-2.13.2-alpha, or use Python 3.6 or lower.
Sources:
https://docs.python.org/3/whatsnew/3.7.html
https://pypi.org/project/spyne/2.13.2a0/

Why do I receive urlopen no attribute error in python 3.7.3?

Im new to python and trying to work on geocode data.
I have written the below code to find the drive time between to geocodes.
import urllib.request
#from urllib.request import urlopen
import simplejson, urllib
orig_lat = 52.2296756
orig_lng = 21.0122287
dest_lat = 52.406374
dest_lng = 16.9251681
orig_coord = orig_lat, orig_lng
dest_coord = dest_lat, dest_lng
url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&language=en-EN&sensor=false".format(str(orig_coord),str(dest_coord))
result= simplejson.load(urllib.urlopen(url))
driving_time = result['rows'][0]['elements'][0]['duration']['value']
However, I receive an error:
Traceback (most recent call last):
File "<ipython-input-154-c5d2043b6825>", line 11, in <module>
result= simplejson.load(urllib.urlopen(url))
AttributeError: module 'urllib' has no attribute 'urlopen'
I have seen other posts about this, but none of them work for me as a solution to this attribute error.
Assuming you're using Python 3, urllib.urlopen has been replaced with urllib.request.urlopen(). Change urllib.urlopen(url) to urllib.request.urlopen(url).
See the Python 3 documentation for more information.

ImportError: No module named 'requests.packages.urllib3.contrib.appengine'

I can't run my script I'm using python3 and I install pyrebase and his dependencies
I got this below exception when I try to run my script on linux ubuntu
Traceback (most recent call last):
File "scrapping2fb.py", line 9, in <module>
import pyrebase
File "/usr/local/lib/python3.4/dist-packages/pyrebase/__init__.py", line 1, in <module>
from .pyrebase import initialize_app
File "/usr/local/lib/python3.4/dist-packages/pyrebase/pyrebase.py", line 19, in <module>
from requests.packages.urllib3.contrib.appengine import is_appengine_sandbox
Can some one help me
Thank you
The script that i try to run
from urllib.request import urlopen ,URLError,HTTPError,Request
from socket import timeout
from bs4 import BeautifulSoup
from time import sleep
import mysql.connector
from datetime import datetime
import pyrebase
def is_exist_firebase_db_AR(siteName,title):#(siteName,title):
global config
global email
global password
firebase = pyrebase.initialize_app(config)
db=firebase.database()
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(email, password)
all_items = db.child("items_ar").get(user['idToken'])
if(all_items.each() is not None):
for item in all_items.each():
if(siteName in item.val().get("nomSite") and title in item.val().get("titre")):
return 1
return 0
This is a problem with the pyrebase package.
Since commit 8e17600ef60de4faf632acb55d15cb3c178de9bb which went into v2.16.0, requests no longer bundle urllib3.
The package pyrebase is relying on this implementation detail, and, like all things that rely on implementation details eventually do, was broken.

ImportError with gevent and requests async module

I'm writing a simple script that:
Loads a big list of URLs
Get the content of each URL making concurrent HTTP requests using requests' async module
Parses the content of the page with lxml in order to check if a link is in the page
If the link is present on the page, saves some info about the page in a ZODB database
When I test the script with 4 or 5 URLs It works well, I only have the following message when the script ends:
Exception KeyError: KeyError(45989520,) in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
But when I try to check about 24000 URLs it fails toward the end of the list (when there are about 400 URLs left to check) with the following error:
Traceback (most recent call last):
File "check.py", line 95, in <module>
File "/home/alex/code/.virtualenvs/linka/local/lib/python2.7/site-packages/requests/async.py", line 83, in map
File "/home/alex/code/.virtualenvs/linka/local/lib/python2.7/site-packages/gevent-1.0b2-py2.7-linux-x86_64.egg/gevent/greenlet.py", line 405, in joinall
ImportError: No module named queue
Exception KeyError: KeyError(45989520,) in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
I tried both with the version of gevent available on pypi and downloading and installing the latest version (1.0b2) from gevent repository.
I cannot understand why this happened, and why it happened only when I check a bunch of URLs. Any suggestions?
Here is the entire script:
from requests import async, defaults
from lxml import html
from urlparse import urlsplit
from gevent import monkey
from BeautifulSoup import UnicodeDammit
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
import transaction
import persistent
import random
storage = FileStorage('Data.fs')
db = DB(storage)
connection = db.open()
root = connection.root()
monkey.patch_all()
defaults.defaults['base_headers']['User-Agent'] = "Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0"
defaults.defaults['max_retries'] = 10
def save_data(source, target, anchor):
root[source] = persistent.mapping.PersistentMapping(dict(target=target, anchor=anchor))
transaction.commit()
def decode_html(html_string):
converted = UnicodeDammit(html_string, isHTML=True)
if not converted.unicode:
raise UnicodeDecodeError(
"Failed to detect encoding, tried [%s]",
', '.join(converted.triedEncodings))
# print converted.originalEncoding
return converted.unicode
def find_link(html_doc, url):
decoded = decode_html(html_doc)
doc = html.document_fromstring(decoded.encode('utf-8'))
for element, attribute, link, pos in doc.iterlinks():
if attribute == "href" and link.startswith('http'):
netloc = urlsplit(link).netloc
if "example.org" in netloc:
return (url, link, element.text_content().strip())
else:
return False
def check(response):
if response.status_code == 200:
html_doc = response.content
result = find_link(html_doc, response.url)
if result:
source, target, anchor = result
# print "Source: %s" % source
# print "Target: %s" % target
# print "Anchor: %s" % anchor
# print
save_data(source, target, anchor)
global todo
todo = todo -1
print todo
def load_urls(fname):
with open(fname) as fh:
urls = set([url.strip() for url in fh.readlines()])
urls = list(urls)
random.shuffle(urls)
return urls
if __name__ == "__main__":
urls = load_urls('urls.txt')
rs = []
todo = len(urls)
print "Ready to analyze %s pages" % len(urls)
for url in urls:
rs.append(async.get(url, hooks=dict(response=check), timeout=10.0))
responses = async.map(rs, size=100)
print "DONE."
I'm not sure what's the source of your problem, but why do you have monkey.patch_all() not at the top of the file?
Could you try putting
from gevent import monkey; monkey.patch_all()
at the top of your main program and see if it fixes anything?
I am such a big n00b but anyway, I can try ... !
I guess you can try to change your import list by this one :
from requests import async, defaults
import requests
from lxml import html
from urlparse import urlsplit
from gevent import monkey
import gevent
from BeautifulSoup import UnicodeDammit
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
import transaction
import persistent
import random
Try this and tell me if it works .. I guess that can solve your problem :)
good day.
I think it's open python bug with number Issue1596321
http://bugs.python.org/issue1596321

ContentHandler is undefined

I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why.
The first file is handlers.py:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
You have to import ContentHandler in handlers.py as follows:
from xml.sax.handler import ContentHandler
This should do it.

Categories

Resources