Permalink
Browse files

pep-8 compliance and minor fixes

  • Loading branch information...
1 parent 2867670 commit 883255cfa8f8c126a1265a9b64ebb9ebf8b458a0 @fiorix committed Mar 9, 2012
View
@@ -54,8 +54,8 @@ def usage(version, target):
use: %s [options]
Options:
-h --help Show this help.
- -g --git Use git's name and email settings, and create a git repo on target
-p --project=NAME Create new cyclone project.
+ -g --git Use in conjunction with -p to make it a git repository.
-m --modname=NAME Use another name for the module [default: project_name]
-v --version=VERSION Set project version [default: %s]
-s --set-pkg-version Set version on package name [default: False]
@@ -73,11 +73,11 @@ def main():
default_target, target = os.getcwd(), None
shortopts = "hgsp:m:v:t:"
- longopts = ["help", "git", "set-pkg-version",
+ longopts = ["help", "git", "set-pkg-version",
"project=", "modname=", "version=", "target="]
try:
opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
- except getopt.GetoptError, err:
+ except getopt.GetoptError:
usage(default_version, default_target)
for o, a in opts:
@@ -115,9 +115,11 @@ def main():
if modname in ("frontend", "tools", "twisted"):
if mod_is_proj is True:
- print("Please specify a different modname, using --modname=name. '%s' is not allowed." % modname)
+ print("Please specify a different modname, using "
+ "--modname=name. '%s' is not allowed." % modname)
else:
- print("Please specify a different modname. '%s' is not allowed." % modname)
+ print("Please specify a different modname. "
+ "'%s' is not allowed." % modname)
sys.exit(1)
if not re.match(r"^[0-9a-z_]+$", modname, re.I):
@@ -131,7 +133,8 @@ def main():
target = default_target
if not (os.access(target, os.W_OK) and os.access(target, os.X_OK)):
- print("Cannot create project on target directory '%s': permission denied" % target)
+ print("Cannot create project on target directory "
+ "'%s': permission denied" % target)
sys.exit(1)
name = "Foo Bar"
@@ -151,13 +154,14 @@ def main():
email = v
skel = zipfile.ZipFile(open(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), "appskel.zip")))
+ os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "appskel.zip")))
if set_pkg_version is True:
- project_name="%s-%s" % (project, version)
+ project_name = "%s-%s" % (project, version)
else:
- project_name=project
- project_path=os.path.join(target, project_name)
+ project_name = project
+ project_path = os.path.join(target, project_name)
new_project(skel=skel,
name=name,
email=email,
View
@@ -46,10 +46,10 @@ def _on_auth(self, user):
"""
-from twisted.python import log, failure
-from cyclone import escape, httpclient
+from cyclone import escape
+from cyclone import httpclient
+from twisted.python import log
-import base64
import binascii
import functools
import hashlib
@@ -66,7 +66,8 @@ class OpenIdMixin(object):
See GoogleMixin below for example implementations.
"""
def authenticate_redirect(self, callback_uri=None,
- ax_attrs=["name","email","language","username"]):
+ ax_attrs=["name", "email",
+ "language", "username"]):
"""Returns the authentication URL for this service.
After authentication, the service will redirect back to the given
@@ -92,7 +93,8 @@ def get_authenticated_user(self, callback):
args = dict((k, v[-1]) for k, v in self.request.arguments.iteritems())
args["openid.mode"] = u"check_authentication"
url = self._OPENID_ENDPOINT + "?" + urllib.urlencode(args)
- callback = self.async_callback(self._on_authentication_verified, callback)
+ callback = self.async_callback(self._on_authentication_verified,
+ callback)
httpclient.fetch(url).addBoth(callback)
def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
@@ -145,7 +147,8 @@ def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
def _on_authentication_verified(self, callback, response):
if response.error or "is_valid:true" not in repr(response.body):
- log.msg("Invalid OpenID response: %s" % (response.error or response.body))
+ log.msg("Invalid OpenID response: %s" % \
+ (response.error or response.body))
callback(None)
return
@@ -158,15 +161,17 @@ def _on_authentication_verified(self, callback, response):
break
def get_ax_arg(uri):
- if not ax_ns: return u""
+ if not ax_ns:
+ return u""
prefix = "openid." + ax_ns + ".type."
ax_name = None
for name, values in self.request.arguments.iteritems():
if values[-1] == uri and name.startswith(prefix):
part = name[len(prefix):]
ax_name = "openid." + ax_ns + ".value." + part
break
- if not ax_name: return u""
+ if not ax_name:
+ return u""
return self.get_argument(ax_name, u"")
email = get_ax_arg("http://axschema.org/contact/email")
@@ -189,9 +194,12 @@ def get_ax_arg(uri):
user["name"] = u" ".join(name_parts)
elif email:
user["name"] = email.split("@")[0]
- if email: user["email"] = email
- if locale: user["locale"] = locale
- if username: user["username"] = username
+ if email:
+ user["email"] = email
+ if locale:
+ user["locale"] = locale
+ if username:
+ user["username"] = username
callback(user)
@@ -293,7 +301,7 @@ def _on_access_token(self, callback, response):
callback(None)
return
access_token = _oauth_parse_response(response.body)
- user = self._oauth_get_user(access_token, self.async_callback(
+ self._oauth_get_user(access_token, self.async_callback(
self._on_oauth_get_user, access_token, callback))
def _oauth_get_user(self, access_token, callback):
@@ -425,19 +433,23 @@ def _on_post(self, new_entry):
all_args = {}
all_args.update(args)
all_args.update(post_args or {})
- consumer_token = self._oauth_consumer_token()
+ self._oauth_consumer_token()
method = "POST" if post_args is not None else "GET"
oauth = self._oauth_request_parameters(
url, access_token, all_args, method=method)
args.update(oauth)
- if args: url += "?" + urllib.urlencode(args)
+ if args:
+ url += "?" + urllib.urlencode(args)
if post_args is not None:
- d = httpclient.fetch(url, method="POST", postdata=urllib.urlencode(post_args))
- d.addCallback(self.async_callback(self._on_twitter_request, callback))
+ d = httpclient.fetch(url, method="POST",
+ postdata=urllib.urlencode(post_args))
+ d.addCallback(self.async_callback(self._on_twitter_request,
+ callback))
else:
d = httpclient.fetch(url)
- d.addCallback(self.async_callback(self._on_twitter_request, callback))
-
+ d.addCallback(self.async_callback(self._on_twitter_request,
+ callback))
+
def _on_twitter_request(self, callback, response):
if response.error:
log.msg("Error response %s fetching %s" % (response.error,
@@ -486,7 +498,7 @@ def get(self):
self.get_authenticated_user(self.async_callback(self._on_auth))
return
self.authorize_redirect()
-
+
def _on_auth(self, user):
if not user:
raise tornado.web.HTTPError(500, "FriendFeed auth failed")
@@ -498,8 +510,10 @@ def _on_auth(self, user):
it is required to make requests on behalf of the user later with
friendfeed_request().
"""
- _OAUTH_REQUEST_TOKEN_URL = "https://friendfeed.com/account/oauth/request_token"
- _OAUTH_ACCESS_TOKEN_URL = "https://friendfeed.com/account/oauth/access_token"
+ _OAUTH_REQUEST_TOKEN_URL = \
+ "https://friendfeed.com/account/oauth/request_token"
+ _OAUTH_ACCESS_TOKEN_URL = \
+ "https://friendfeed.com/account/oauth/access_token"
_OAUTH_AUTHORIZE_URL = "https://friendfeed.com/account/oauth/authorize"
_OAUTH_NO_CALLBACKS = True
@@ -544,19 +558,22 @@ def _on_post(self, new_entry):
all_args = {}
all_args.update(args)
all_args.update(post_args or {})
- consumer_token = self._oauth_consumer_token()
+ self._oauth_consumer_token()
method = "POST" if post_args is not None else "GET"
oauth = self._oauth_request_parameters(
url, access_token, all_args, method=method)
args.update(oauth)
- if args: url += "?" + urllib.urlencode(args)
+ if args:
+ url += "?" + urllib.urlencode(args)
if post_args is not None:
- d = httpclient.fetch(url, method="POST", postdata=urllib.urlencode(post_args))
- d.addCallback(self.async_callback(self._on_friendfeed_request, callback))
+ d = httpclient.fetch(url, method="POST",
+ postdata=urllib.urlencode(post_args))
+ d.addCallback(self.async_callback(self._on_friendfeed_request,
+ callback))
else:
httpclient.fetch(url).addCallback(self.async_callback(
self._on_friendfeed_request, callback))
-
+
def _on_friendfeed_request(self, callback, response):
if response.error:
log.msg("Error response %s fetching %s" % (response.error,
@@ -610,10 +627,11 @@ def _on_auth(self, user):
"""
_OPENID_ENDPOINT = "https://www.google.com/accounts/o8/ud"
- _OAUTH_ACCESS_TOKEN_URL = "https://www.google.com/accounts/OAuthGetAccessToken"
+ _OAUTH_ACCESS_TOKEN_URL = \
+ "https://www.google.com/accounts/OAuthGetAccessToken"
def authorize_redirect(self, oauth_scope, callback_uri=None,
- ax_attrs=["name","email","language","username"]):
+ ax_attrs=["name", "email", "language", "username"]):
"""Authenticates and authorizes for the given Google resource.
Some of the available resources are:
@@ -826,15 +844,16 @@ def _parse_response(self, callback, response):
return
if isinstance(json, dict) and json.get("error_code"):
log.msg("Facebook error: %d: %r" % \
- (json["error_code"], json.get("error_msg")))
+ (json["error_code"], json.get("error_msg")))
callback(None)
return
callback(json)
def _signature(self, args):
parts = ["%s=%s" % (n, args[n]) for n in sorted(args.keys())]
body = "".join(parts) + self.settings["facebook_secret"]
- if isinstance(body, unicode): body = body.encode("utf-8")
+ if isinstance(body, unicode):
+ body = body.encode("utf-8")
return hashlib.md5(body).hexdigest()
@@ -852,7 +871,7 @@ def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
base_elems.append(normalized_url)
base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
for k, v in sorted(parameters.items())))
- base_string = "&".join(_oauth_escape(e) for e in base_elems)
+ base_string = "&".join(_oauth_escape(e) for e in base_elems)
key_elems = [consumer_token["secret"]]
key_elems.append(token["secret"] if token else "")
View
@@ -25,6 +25,7 @@
_handlers = []
_BaseHandler = None
+
class Router:
def __init__(self):
self.items = []
@@ -39,6 +40,7 @@ def __call__(self, *args, **kwargs):
setattr(obj, method.lower(), callback)
return obj
+
def route(path=None, method="GET", callback=None, **kwargs):
if callable(path):
path, callback = None, path
View
@@ -33,6 +33,7 @@
agent = Agent(reactor)
+
class StringProducer(object):
implements(IBodyProducer)
@@ -44,8 +45,11 @@ def startProducing(self, consumer):
consumer.write(self.body)
return defer.succeed(None)
- def pauseProducing(self): pass
- def stopProducing(self): pass
+ def pauseProducing(self):
+ pass
+
+ def stopProducing(self):
+ pass
class Receiver(Protocol):
@@ -97,7 +101,7 @@ def fetch(self):
#print("redirecting to:", location)
response = yield agent.request(
- "GET", #self.method,
+ "GET", # self.method,
location,
request_headers,
self.body_producer)
@@ -128,7 +132,8 @@ def __getattr__(self, attr):
return functools.partial(self.__rpcRequest, attr)
def __rpcRequest(self, method, *args):
- q = escape.json_encode({"method":method, "params":args, "id":self.__rpcId})
+ q = escape.json_encode({"method": method, "params": args,
+ "id": self.__rpcId})
self.__rpcId += 1
r = defer.Deferred()
d = fetch(self.__rpcUrl, method="POST", postdata=q)
View
@@ -24,7 +24,7 @@
from twisted.python import log
from twisted.protocols import basic
-from twisted.internet import defer, protocol
+from twisted.internet import defer
from cyclone.escape import utf8, native_str, parse_qs_bytes
from cyclone import httputil
@@ -72,7 +72,7 @@ def notifyFinish(self):
def lineReceived(self, line):
if line:
- self._headersbuffer.append(line+self.delimiter)
+ self._headersbuffer.append(line + self.delimiter)
else:
buff = "".join(self._headersbuffer)
self._headersbuffer = []
@@ -137,7 +137,8 @@ def _on_headers(self, data):
except ValueError:
raise _BadRequestException("Malformed HTTP request line")
if not version.startswith("HTTP/"):
- raise _BadRequestException("Malformed HTTP version in HTTP Request-Line")
+ raise _BadRequestException(
+ "Malformed HTTP version in HTTP Request-Line")
headers = httputil.HTTPHeaders.parse(data[eol:])
self._request = HTTPRequest(
connection=self, method=method, uri=uri, version=version,
@@ -283,7 +284,8 @@ def __init__(self, method, uri, version="HTTP/1.0", headers=None,
self._start_time = time.time()
self._finish_time = None
- scheme, netloc, path, query, fragment = urlparse.urlsplit(native_str(uri))
+ scheme, netloc, path, query, fragment = \
+ urlparse.urlsplit(native_str(uri))
self.path = path
self.query = query
arguments = parse_qs_bytes(query)
Oops, something went wrong.

0 comments on commit 883255c

Please sign in to comment.