web.py printing the html code on Apache server - python

I have web.py configured for my Apache server by installing flups. However when I go to my application, the html code is printed instead of the html page. (See below).
Content-Type: text/html
<HTML><HEAD><TITLE>Login Details</TITLE></HEAD><BODY>.......</BODY></HTML>
I created another file Test.py in the same directory with the following code
#!/usr/bin/python
print "Content-Type: text/html\n\n"
print "<html><head></head><body>Present</body></html>"
This prints out the page fine. Both the files have the same executable permissions.(chmod 755).
Any ideas why this is happening?
Update: Just found out. If I change the return statement to a print inside the GET method for my app, it prints out the form fine, but also prints out the cookie, session id, etc.. at the end. What do I need to configure to make the return work as expected?
Adding a sample code which would cause the issue:
#!/usr/bin/python
import web
urls = ("/CodeAnalyzer", "CodeAnalyzer")
app = web.application(urls, globals())
class CodeAnalyzer:
def GET(self):
init="Content-Type: text/html\n\n"
form="<html><head></head><body>Hello World</body><html>"
return init+form
if __name__ == "__main__":
app.run()

The issue was in the line
init="Content-Type: text/html\n\n"
That was the incorrect way to pass the header in web.py. The issue was resolved after replacing it with
web.header('Content-Type','text/html; charset=utf-8', unique=True)

Related

Python: WSGI crashing with no error

I'm currently developing a web service in WSGI, but the script crashes on the line where I am executing my query. I'm using the exact same code as other working web services, and even simplified my query for testing purposes, but to no avail.
The real problem is that while I can manually print stuff to the error_log specified in my VirtualHost, there is no log for the error that occurs when the script crashes.
All I know now is that the print before the line is written to the log, but the print after isn't. How can I print the error to the log and get to the root of my problem?
The code (simplified a bit):
webservice.wsgi:
def application(environ, start_response):
ENV = environ.get('APPLICATION_ENV', 'DEV')
connector = ConnectorObj(confParams['dbname'], confParams['host'], confParams['port'], confParams['user'], confParams['password'])
method = environ.get('REQUEST_METHOD', '')
if (method == 'POST'):
content_body = json.loads(request_body)
han = HandlerObj(connector)
res = han.getBld()
start_response('200 OK', [('content-type', 'application/json; charset=utf-8'), ('Access-Control-Allow-Origin', '*')])
return(res)
getBld:
def getBld(self):
print "execute query"
self.cur.execute("""
SELECT * FROM adr.bld
""")
print "after executing query"
After doing the post call, I can see that "execute query" is being printed to the error_log, but then it just crashes and doesn't get to "after executing query".
Again, I'm not asking what is wrong with my actual code (I would have to provide much more in order to make sense of it), but simply how I can get an error trace somehow so I can start to debug it myself..
It depends on the database you use. If it is some open source I would recommend taking the source codes and compiling it with enabled debug mode which will result DB to create log file for itself which can point to the error.

why bottle does not show the page I returned?

I am new to bottle. I have searched for the answer but could not get any.
Is there anyway to load a page without redirect?
The code is like this:
from bottle import get, run, template
#get('/list/item')
def listItems():
r = requests.get('my/url/which/works/')
return r.content
if __name__ == '__main__':
run(host='localhost', port=8080 )
and the webpage is empty. I have also tried return r.text, return template(r.content), return str(r.content), return str(r.content.decode('utf-8')), and
nf = urllib.urlopen('my/url/whick/works')
return nf.read()
none of them returns the page I want.
However, if I write this return r.content[0], it works. the page will show the first letter, which is '<'. But if I write return r.content[0:100], it returns a empty page again.
If I run the requests in command line, this is what it returns:
>>> import requests
>>> r = requests.get('my/url/which/works/')
>>>
>>> r.content
'<?xml version="1.0" encoding="utf-8" ?> \n<body copyright="...>\n</body>\n'
Is that possible that anyone can help about this? Thank you very much.
Your question doesn't specify what you expect to see when your code works as expected, but this may help you:
from bottle import get, run, template, response
#get('/list/item')
def listItems():
r = requests.get('my/url/which/works/')
response.content_type = 'text/plain' # added this
return r.content
...
The only change is that your webserver will now be setting the content type of the response to text/plain, which should make your browser render the page.
Longer term, if (as I'm inferring from your question) you intend to return XML responses, then I suggest either installing a browser plugin (here's an example), or, better yet, use curl or wget to see the precise response. This will help you debug your server's responses.

Why my simple pyramid application cannot work with pexpect?

I have a very simple pyramid application which serves a simple static page. Let's say its name is mypyramid and uses port 9999.
If I launch mypyramid in another linux console manually, then I can use the following code to print out the html string.
if __name__ == "__main__":
import urllib2
print 'trying to download url'
response = urllib2.urlopen('http://localhost:9999/index.html')
html = response.read()
print html
But I want to launch mypyramid in an application automatically.
So in my another application, I used pexpect to launch mypyramid, and then try to get the html string from http://localhost:9999/index.html.
def _start_mypyramid():
p = pexpect.spawn(command='./mypyramid')
return p
if __name__ == "__main__":
p = _start_mypyramid()
print p
print 'mypyramid started'
import urllib2
print 'trying to download url'
response = urllib2.urlopen('http://localhost:9999/index.html')
html = response.read()
print html
It seems mypyramid has been successfully launched using pexpect, as I can see the print of the process and mypyramid started has been reached.
However, the application is just hanging after trying to download url, and I can't get anything.
What is the solution? I mean I thought pexpect would create another process. If that's true, then why it is stopping the retrieval of the html?
My guess would be that the child returned by pexpect.spawn needs to communicate.
It attempts to write but nobody reads, so the app stops. (I am only guessing though).
If you do not have any reason to use pexpect (which you probably don't if you do not communicate with the child process), why wouldn't you just go for a standard module subprocess?

How to override the server version string with wsgiref.simple_server?

Using Python 2.7.2 on OSX (darwin), I would like to hide or customize the "Server" response header sent by the wsgiref.simple_server.make_server().
I tried many things without any success and was pretty sure this sample code should work:
from wsgiref import simple_server
class MyWSGIRequestHandler(simple_server.WSGIRequestHandler):
server_version = "X/1"
sys_version = "Y/2"
httpd = simple_server.make_server('', 8082, simple_server.demo_app, handler_class=MyWSGIRequestHandler)
print "version_string: %s %s" % (httpd.RequestHandlerClass.server_version, httpd.RequestHandlerClass.sys_version)
# it prints "X/1 Y/2"
httpd.serve_forever()
But it's always the same and there's no way to get rid of the "Server: WSGIServer/0.1 Python/2.7.2" sent by the server. I've also tried to override the version_string method in my class, for example with something like that:
class MyWSGIRequestHandler(simple_server.WSGIRequestHandler):
def version_string(self):
return "42"
It changes nothing, I really don't understand what's happening here.
Can someone help me please?
I've finally found the solution, no need to override WSGIRequestHandler.
from wsgiref.simple_server import ServerHandler
ServerHandler.server_software = "Fake Server Name Here"
And then you can call make_server().

How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK?

When I run this code on my computer with the help of "Google App Engine SDK", it displays (in my browser) the HTML code of the Google home page:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
print result.content
How can I make it display the page itself? I mean I want to see that page in my browser the way it would normally be seen by any user of the internet.
Update 1:
I see I have received a few questions that look a bit complicated to me, although I definitely remember I was able to do it, and it was very simple, except i don't remember what exactly i changed then in this code.
Perhaps, I didn't give You all enough details on how I run this code and where I found it. So, let me tell You what I did. I only installed Python 2.5 on my computer and then downloaded "Google App Engine SDK" and installed it, too. Following the instructions on "GAE" page (http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html) I created a directory and named it “My_test”, then I created a “my_test.py” in it containing that small piece of the code that I mentioned in my question.
Then, continuing to follow on the said instructions, I created an “app.yaml” file in it, in which my “my_test.py” file was mentioned. After that in “Google App Engine Launcher” I found “My_test” directory and clicked on Run button, and then on Browse. Then, having visited this URL http://localhost:8080/ in my web browser, I saw the results.
I definitely remember I was able to display any page in my browser in this way, and it was very simple, except I don’t remember what exactly I changed in the code (it was a slight change). Now, all I can see is a raw HTML code of a page, but not a page itself.
Update 2:
(this update is my response to wescpy)
Hello, wescpy!!! I've tried Your updated code and something didn't work well there. Perhaps, it's because I am not using a certain framework that I am supposed to use for this code. Please, take a look at this screen shot (I guess You'll need to right-click this image to see it in better resolution):
(source: narod.ru)
Is not that easy, you have to parse content and adjust relative to absolute paths for images and javascripts.
Anyway, give it a try adding the correct Content-Type:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
print 'Content-Type: text/html'
print ''
print result.content
a more complete example would look something like this:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
class MainHandler(webapp.RequestHandler):
def get(self):
url = "http://www.google.com/"
result = urlfetch.fetch(url)
self.response.out.write(result.content)
application = webapp.WSGIApplication([
('/', MainHandler),
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
but as others' have said, it's not that easy to do because you're not in the server's domain, meaning the pages will likely not look correct due to missing static content (JS, CSS, and/or images)... unless full pathnames are used or everything that's needed is embedded into the page itself.
UPDATE 1:
as mentioned before, you cannot just download the HTML source and expect things to render correctly because you don't necessarily have access to the static data. if you really want to render it as it was meant to be seen, you have to just redirect... here's the modified piece of code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
class MainHandler(webapp.RequestHandler):
def get(self):
url = "http://www.google.com/"
self.redirect(url)
application = webapp.WSGIApplication([
('/', MainHandler),
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
UPDATE 2:
sorry! it was a cut-n-paste error. now try it.
special characters such as <> etc are likely encoded, you'd have to decode them again for the browser to interpet it as code.

Categories