Skip to content

Commit

Permalink
Reformat files with black
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigc committed Sep 14, 2020
1 parent c0235b6 commit aea5c7e
Show file tree
Hide file tree
Showing 18 changed files with 86 additions and 62 deletions.
9 changes: 5 additions & 4 deletions docs/web/examples/advogato.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,25 @@
from twisted.web.xmlrpc import Proxy
from twisted.internet import reactor

class AddDiary:

class AddDiary:
def __init__(self, name, password):
self.name = name
self.password = password
self.proxy = Proxy(b'http://advogato.org/XMLRPC')
self.proxy = Proxy(b"http://advogato.org/XMLRPC")

def __call__(self, filename):
with open(filename) as f:
self.data = f.read()
d = self.proxy.callRemote('authenticate', self.name, self.password)
d = self.proxy.callRemote("authenticate", self.name, self.password)
d.addCallbacks(self.login, self.noLogin)

def noLogin(self, reason):
print("could not login")
reactor.stop()

def login(self, cookie):
d = self.proxy.callRemote('diary.set', cookie, -1, self.data)
d = self.proxy.callRemote("diary.set", cookie, -1, self.data)
d.addCallbacks(self.setDiary, self.errorSetDiary)

def setDiary(self, response):
Expand All @@ -42,6 +42,7 @@ def errorSetDiary(self, error):
print("could not set diary", error)
reactor.stop()


diary = AddDiary(sys.argv[1], getpass())
diary(sys.argv[2])
reactor.run()
5 changes: 3 additions & 2 deletions docs/web/examples/dlpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# the page to "foo".
url = sys.argv[1].encode("ascii")
downloadPage(url, "foo").addCallbacks(
lambda value:reactor.stop(),
lambda error:(println("an error occurred",error),reactor.stop()))
lambda value: reactor.stop(),
lambda error: (println("an error occurred", error), reactor.stop()),
)
reactor.run()
11 changes: 7 additions & 4 deletions docs/web/examples/fortune.rpy
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ from twisted.web.resource import Resource
from twisted.web import server
from twisted.internet import utils


class FortuneResource(Resource):
"""
This resource will only respond to HEAD & GET requests.
"""

# Link your fortune program to /usr/games or change the path.
fortune = "/usr/games/fortune"

Expand All @@ -39,10 +41,11 @@ class FortuneResource(Resource):
"""
request.write(b"<pre>\n")
deferred = utils.getProcessOutput(self.fortune)
deferred.addCallback(lambda s:
(request.write(s+b"\n"), request.finish()))
deferred.addErrback(lambda s:
(request.write(str(s).encode("utf8")), request.finish()))
deferred.addCallback(lambda s: (request.write(s + b"\n"), request.finish()))
deferred.addErrback(
lambda s: (request.write(str(s).encode("utf8")), request.finish())
)
return server.NOT_DONE_YET


resource = FortuneResource()
5 changes: 3 additions & 2 deletions docs/web/examples/getpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

url = sys.argv[1].encode("ascii")
getPage(url).addCallbacks(
callback=lambda value:(println(value),reactor.stop()),
errback=lambda error:(println("an error occurred", error),reactor.stop()))
callback=lambda value: (println(value), reactor.stop()),
errback=lambda error: (println("an error occurred", error), reactor.stop()),
)
reactor.run()
12 changes: 7 additions & 5 deletions docs/web/examples/hello.rpy
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,25 @@ import time

now = time.ctime()

d = '''\
d = """\
<HTML><HEAD><TITLE>Hello Rpy</TITLE>
<H1>Hello World, It is Now {now}</H1>
<UL>
'''.format(now=now)
""".format(
now=now
)

for i in range(10):
d += "<LI>{i}".format(i=i)

d += '''\
d += """\
</UL>
</BODY></HTML>
'''
"""

data = d.encode("utf8")

resource = static.Data(data, 'text/html')
resource = static.Data(data, "text/html")
17 changes: 9 additions & 8 deletions docs/web/examples/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ def dataReceived(self, data):
"""
Print out the html page received.
"""
print('Got some:', data)
print("Got some:", data)

def connectionLost(self, reason):
if not reason.check(ResponseDone):
reason.printTraceback()
else:
print('Response done')
print("Response done")
self.onConnLost.callback(None)


Expand All @@ -47,27 +47,28 @@ def main(reactor, url):
We create a custom UserAgent and send a GET request to a web server.
"""
url = url.encode("ascii")
userAgent = 'Twisted/{} (httpclient.py)'.format(version.short()).encode("ascii")
userAgent = "Twisted/{} (httpclient.py)".format(version.short()).encode("ascii")
agent = Agent(reactor)
d = agent.request(
b'GET', url, Headers({b'user-agent': [userAgent]}))
d = agent.request(b"GET", url, Headers({b"user-agent": [userAgent]}))

def cbResponse(response):
"""
Prints out the response returned by the web server.
"""
pprint(vars(response))
proto = WriteToStdout()
if response.length is not UNKNOWN_LENGTH:
print('The response body will consist of', response.length, 'bytes.')
print("The response body will consist of", response.length, "bytes.")
else:
print('The response body length is unknown.')
print("The response body length is unknown.")
response.deliverBody(proto)
return proto.onConnLost

d.addCallback(cbResponse)
d.addErrback(log.err)
d.addBoth(lambda ign: reactor.callWhenRunning(reactor.stop))
reactor.run()


if __name__ == '__main__':
if __name__ == "__main__":
main(reactor, *sys.argv[1:])
10 changes: 8 additions & 2 deletions docs/web/examples/logging-proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,31 @@
from twisted.internet import reactor
from twisted.web import proxy, http


class LoggingProxyRequest(proxy.ProxyRequest):
def process(self):
"""
It's normal to see a blank HTTPS page. As the proxy only works
with the HTTP protocol.
"""
print("Request from %s for %s" % (
self.getClientIP(), self.getAllHeaders()['host']))
print(
"Request from %s for %s"
% (self.getClientIP(), self.getAllHeaders()["host"])
)
try:
proxy.ProxyRequest.process(self)
except KeyError:
print("HTTPS is not supported at the moment!")


class LoggingProxy(proxy.Proxy):
requestFactory = LoggingProxyRequest


class LoggingProxyFactory(http.HTTPFactory):
def buildProtocol(self, addr):
return LoggingProxy()


reactor.listenTCP(8080, LoggingProxyFactory())
reactor.run()
2 changes: 2 additions & 0 deletions docs/web/examples/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
from twisted.web import proxy, http
from twisted.internet import reactor


class ProxyFactory(http.HTTPFactory):
def buildProtocol(self, addr):
return proxy.Proxy()


reactor.listenTCP(8080, ProxyFactory())
reactor.run()
6 changes: 4 additions & 2 deletions docs/web/examples/report.rpy
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ from twisted.web.resource import Resource


class ReportResource(Resource):

def render_GET(self, request):
path = request.path
host = request.getHost().host
Expand All @@ -39,8 +38,11 @@ class ReportResource(Resource):
<LI>My URI to me is {uri}
</UL>
</body>
</html>""".format(path=path, host=host, port=port, secure=secure, url=url, uri=uri)
</html>""".format(
path=path, host=host, port=port, secure=secure, url=url, uri=uri
)

return output.encode("utf8")


resource = ReportResource()
2 changes: 1 addition & 1 deletion docs/web/examples/reverse-proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
from twisted.internet import reactor
from twisted.web import proxy, server

site = server.Site(proxy.ReverseProxyResource('example.com', 80, b''))
site = server.Site(proxy.ReverseProxyResource("example.com", 80, b""))
reactor.listenTCP(8080, site)
reactor.run()
8 changes: 4 additions & 4 deletions docs/web/examples/rootscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,21 @@
from twisted.web import vhost, static, script, server
from twisted.application import internet, service

default = static.Data('text/html', '')
default = static.Data("text/html", "")
# Setting up vhost resource.
default.putChild(b'vhost', vhost.VHostMonsterResource())
default.putChild(b"vhost", vhost.VHostMonsterResource())
resource = vhost.NameVirtualHost()
resource.default = default
# Here we use /var/www/html/ as our root diretory for the web server, you can
# change it to whatever directory you want.
root = static.File("/var/www/html/")
root.processors = {'.rpy': script.ResourceScript}
root.processors = {".rpy": script.ResourceScript}
# addHost binds domain name example.com to our root resource.
resource.addHost("example.com", root)

# Setup Twisted Application.
site = server.Site(resource)
application = service.Application('vhost')
application = service.Application("vhost")
sc = service.IServiceCollection(application)
# Only the processes owned by the root user can listen @ port 80, change the
# port number here if you don't want to run it as root.
Expand Down
6 changes: 3 additions & 3 deletions docs/web/examples/silly-web.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
from twisted.spread import pb

# The "master" server
site = server.Site(distrib.ResourceSubscription('unix', '.rp'))
site = server.Site(distrib.ResourceSubscription("unix", ".rp"))
reactor.listenTCP(19988, site)

# The "slave" server
fact = pb.PBServerFactory(distrib.ResourcePublisher(server.Site(static.File('static'))))
fact = pb.PBServerFactory(distrib.ResourcePublisher(server.Site(static.File("static"))))

reactor.listenUNIX('./.rp', fact)
reactor.listenUNIX("./.rp", fact)
reactor.run()
1 change: 1 addition & 0 deletions docs/web/examples/soap.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def soap_echo(self, x):

def soap_add(self, a=0, b=0):
return a + b

soap_add.useKeywords = 1

def soap_deferred(self):
Expand Down
8 changes: 4 additions & 4 deletions docs/web/examples/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@

root = static.File("static")
root.processors = {
'.cgi': twcgi.CGIScript,
'.epy': script.PythonScript,
'.rpy': script.ResourceScript,
".cgi": twcgi.CGIScript,
".epy": script.PythonScript,
".rpy": script.ResourceScript,
}
root.putChild(b'vhost', vhost.VHostMonsterResource())
root.putChild(b"vhost", vhost.VHostMonsterResource())
site = server.Site(root)
reactor.listenTCP(1999, site)
reactor.run()
16 changes: 8 additions & 8 deletions docs/web/examples/webguard.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,37 +27,37 @@ class GuardedResource(resource.Resource):
A resource which is protected by guard and requires authentication in order
to access.
"""

def getChild(self, path, request):
return self


def render(self, request):
return b"Authorized!"



@implementer(IRealm)
class SimpleRealm(object):
"""
A realm which gives out L{GuardedResource} instances for authenticated
users.
"""

def requestAvatar(self, avatarId, mind, *interfaces):
if resource.IResource in interfaces:
return resource.IResource, GuardedResource(), lambda: None
raise NotImplementedError()



def main():
log.startLogging(sys.stdout)
checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe=b'blow')]
checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe=b"blow")]
wrapper = guard.HTTPAuthSessionWrapper(
Portal(SimpleRealm(), checkers),
[guard.DigestCredentialFactory('md5', b'example.com')])
reactor.listenTCP(8889, server.Site(
resource = wrapper))
[guard.DigestCredentialFactory("md5", b"example.com")],
)
reactor.listenTCP(8889, server.Site(resource=wrapper))
reactor.run()

if __name__ == '__main__':

if __name__ == "__main__":
main()
11 changes: 4 additions & 7 deletions docs/web/examples/xmlrpc-debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,31 @@
from twisted.internet import reactor



class DebuggingQueryFactory(QueryFactory):
""" Print the server's raw responses before continuing with parsing. """

def parseResponse(self, contents):
print(contents) # show the raw XML-RPC string
return QueryFactory.parseResponse(self, contents)



def printValue(value):
print(repr(value))
reactor.stop()



def printError(error):
print('error', error)
print("error", error)
reactor.stop()



proxy = Proxy(b'https://bugzilla.redhat.com/xmlrpc.cgi')
proxy = Proxy(b"https://bugzilla.redhat.com/xmlrpc.cgi")

# Enable our debugging factory for our client:
proxy.queryFactory = DebuggingQueryFactory

# "Bugzilla.version" returns the Bugzilla software version,
# like "{'version': '5.0.4.rh11'}":
proxy.callRemote('Bugzilla.version').addCallbacks(printValue, printError)
proxy.callRemote("Bugzilla.version").addCallbacks(printValue, printError)

reactor.run()
Loading

0 comments on commit aea5c7e

Please sign in to comment.