Twisted: static URL dispatch 'No Such Resource' error - python

I'm learning to use twisted.web from web-in-60-seconds . In the section Static URL Dispatch (link here), I ran the code as it is, and when I connect to localhost at port 8880 it displays 'No Such Response' error. Here's the code.
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor, endpoints
from twisted.web.static import File
root = Resource()
root.putChild("foo", File("/tmp"))
root.putChild("bar", File("/lost+found"))
root.putChild("baz", File("/opt"))
factory = Site(root)
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8880)
endpoint.listen(factory)
reactor.run()
urls tried
http://localhost:8880/foo
http://localhost:8880/bar
http://localhost:8880/baz
I tried changing paths inside File object and tried some random ports and it still isn't working. What's wrong with this ?

Related

Cannot connect to my custom simple FTP server

I have tried to create a simple FTP server and add some users to it where each user has is own directory.
from twisted.cred.checkers import AllowAnonymousAccess, InMemoryUsernamePasswordDatabaseDontUse
from twisted.cred.portal import Portal
from twisted.internet import reactor
from twisted.protocols.ftp import FTPFactory, FTPRealm
checker = InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("achiya", "0208")
checker.addUser('nitai', '1234')
checker.addUser("guest", "1234")
portal = Portal(FTPRealm("./public", "./MyUsers"), [AllowAnonymousAccess(), checker])
factory = FTPFactory(portal)
reactor.listenTCP(21, factory)
reactor.run()
This is the code to the FTP server. When i try to connect to the FTP server with FileZilla it cannot connect to any new user that I am adding. Am I doing something wrong in the code or something? Thanks for the help!

Python Twisted Authentication Without HTTP Authentication

I'm setting up a Flask server, and want to use a Twisted ReverseProxyResource to proxy over another local server. In Flask, I have a current_user.is_authenticated boolean which I use to protect pages. How can I lock the ReverseProxyResource using this variable, so that it cannot be accessed when a user is logged out? The twisted.web.guard module requires me to set up another HTTP authentication system entirely, and the library doesn't seem to have any other built-in solution.
I've set up some demo code, (based off a previous question) attempting to place the Flask server inside of the Twisted reactor. I'm using the ReverseProxyResource to allow for two-way communication with a Shellinabox server on port 4200.
from flask import Flask
from twisted.internet import reactor
from twisted.web.proxy import ReverseProxyResource
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
app = Flask(__name__)
#app.route('/example')
def index():
return 'Flask within Twisted?'
flask_site = WSGIResource(reactor, reactor.getThreadPool(), app)
root = Resource()
site_example = ReverseProxyResource('localhost', 4200, b'')
root.putChild(b'ssh', site_example)
reactor.listenTCP(8081, Site(root))
reactor.run()
I'd be okay switching to another reverse proxy, but only Twisted has worked so far. I'm also not wanting to switch to the Klein framework due to what I already have established in Flask.

Get current URL in Twisted

I wrote a script in twisted that proxies websites, and I'm just wondering if there's a way to get the current url in Twisted? or even let me know when the URL changes? Thanks!
from twisted.internet import reactor
from twisted.web import proxy, server
site = server.Site(proxy.ReverseProxyResource('www.website.com', 80, ''.encode("utf-8")))
reactor.listenTCP(80, site)
reactor.run()

Tornado web server in webfaction

I am starting with web development. I am trying to develop and webapp using the Instagram API and Django. I was looking that a lot of people it's using Tornado Web Server for Real Time Subscriptions. So I am using Webfaction as a host and found this code so I can wrap my Django project with the "WSGI Container" that Tornado Web Server provides:
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import tornado.web
import sys
import django.core.handlers.wsgi
sys.path.append('/path/to/project')
class HelloHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello from tornado')
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' # path to your settings module
wsgi_app = tornado.wsgi.WSGIContainer(django.core.handlers.wsgi.WSGIHandler())
tornado_app = tornado.web.Application(
[
('/hello-tornado', HelloHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app)),
]
)
http_server = tornado.httpserver.HTTPServer(tornado_app)
http_server.listen(8080)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
So I run this python script inside my Webfaction server and everytime I try to access "http://mywebsite.com/hello-tornado/" does not seem to work. I know I am running that Tornado web server on that port but do not know how too access from the browser or something like that. What I am doing wrong here? Thanks for your help and patience. Will cyber high-five for every answer.
EDIT: What I am really trying to do is that I want to receive all the calls from the subscriptions that I make with the Instagram RealTime Subscription API through Tornado, for that I have a callback url "http://mysite.com/sub" and I want to be able to receive through Tornado.
You are starting the server at port 8080, Web browsers use port 80 by default, try using: http://mywebsite.com:8080/hello-tornado
if you want to use port 80 and you already have a web server running in the box you can try following Ali-Akber Saifee suggestion, or run the WSGI application directly from the server, using something like mod_python (http://www.modpython.org), you will lose the ability to run Tornado code, but Django will work.
You have to create a custom app (listening on port), note the port that is assigned to your app then configure tornado to serve on that port: http_server.listen(my port)
You can also avoid tornado and start directly by installing a django app.

A socket operation was attempted to an unreachable network in python httplib

I am trying to make a REST client from django using httplib . But it is refusing the connection
I tried the following
import hashlib
import hmac
from django.shortcuts import render_to_response
from django.template import RequestContext
def loginAction(request):
username=request.POST['email']
password=request.POST['password']
import httplib, urllib
params = urllib.urlencode({'username': username})
#hash username here to authenticate
digest=hmac.new("qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50", str(request.POST['password']),hashlib.sha1).hexdigest()
auth=username+":"+digest
headers = {"Content-type": "application/json","Accept": "text/plain","Authorization":auth}
conn = httplib.HTTPConnection("10.0.2.2",8000)
conn.request("POST", "/api/ecp/profile/", params, headers)
but is giving following error
[Errno 10051] A socket operation was attempted to an unreachable network
What could be the issue?
The error indicates that your the machine you are running this script on cannot reach the destination IP address (10.0.2.2), as it doesn't have a network route configured from one to the other.
This is a problem with your internal network (10.x.x.x IP addresses are always private network addresses). If you are running this script on a different network from the machine you are trying to reach, you'll need a public IP address for it instead.

Categories

Resources