PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, June 24, 2022

[FIXED] How to run twisted with flask?

 June 24, 2022     flask, python, reverse-proxy, twisted     No comments   

Issue

I wanna be able to run multiple twisted proxy servers on different directories on the same port simultaneously, and I figured I might use flask. so here's my code:

from flask import Flask
from twisted.internet import reactor
from twisted.web import proxy, server

app = Flask(__name__)
@app.route('/example')
def index():
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''.encode("utf-8")))
    reactor.listenTCP(80, site)
    reactor.run()

app.run(port=80, host='My_IP')

But whenever I run this script, I get an Internal Server Error, I'm assuming because when app.run is called on port 80, the reactor.run can't be listening on port 80 as well. I wondering if there is some kind of work around to this, or what it is I'm doing wrong. Any help is greatly appreciated, Thanks!!


Solution

You should give klein a try. It's made and used by most of the twisted core devs. The syntax is very much like flask so you won't have to rewrite much if you already have a working flask app. So something like the following should work:

from twisted.internet import reactor
from twisted.web import proxy, server
from klein import Klein

app = Klein()

@app.route('/example')
def home(request):
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''.encode("utf-8")))
    reactor.listenTCP(80, site)

app.run('localhost', 8000)        # start the klein app on port 8000 and reactor event loop

Links

  • Klein Docs
  • Klein Github


Answered By - notorious.no
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing