Skip to content

Instantly share code, notes, and snippets.

@yangjuven
Created February 11, 2012 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangjuven/1799560 to your computer and use it in GitHub Desktop.
Save yangjuven/1799560 to your computer and use it in GitHub Desktop.
find bottleneck of wsgi service using python cProfile
#!/usr/bin/env python
# -*- coding: gb2312 -*-
# $Id$
import os, sys, cProfile
from wsgi_handler import application
def wsgi():
environ = dict(os.environ.items())
environ.update({
"SCRIPT_NAME": "/gs2/union",
"REQUEST_METHOD": "GET",
"PATH_INFO": "/adjs/6085502/1/1",
"QUERY_STRING": "link_id=62",
"REMOTE_ADDR": "218.107.55.253",
"HTTP_REFERER": "http://xx.xx.xx",
})
headers_set = []
headers_sent = []
def write(data):
if not headers_set:
raise AssertionError("write() before start_response()")
elif not headers_sent:
# Before the first output, send the stored headers
status, response_headers = headers_sent[:] = headers_set
sys.stdout.write("Status: %s\r\n" % status)
for header in response_headers:
sys.stdout.write("%s: %s\r\n" % header)
sys.stdout.write("\r\n")
sys.stdout.write(data)
sys.stdout.flush()
def start_response(status, response_headers, exc_info=None):
if exc_info:
try:
if headers_sent:
# Re-raise original exception if headers sent
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None # avoid dangling circular ref
elif headers_set:
raise AssertionError("Headers already set!")
headers_set[:] = [status, response_headers]
return write
result = application(environ, start_response)
try:
for data in result:
if data: # don"t send headers until body appears
write(data)
if not headers_sent:
write("") # send headers now if body was empty
finally:
if hasattr(result, "close"):
result.close()
wsgi()
def benchemark():
for i in range(1000):
wsgi()
cProfile.run("benchemark()", "cProfile.log")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment