Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

python - How to programmatically communicate with Apache?

So many web applications these days run on their own microservers, it can be hard to implement them on shared hosting platforms. The apps listen on a dedicated port you can customize or reverse proxy, but shared hosting usually only has 80 and 443 open.

Just as an example, the handy web-based editor ICEcoder is a PHP application, so you just drop the files in a directory and away you go. However, the Cloud9 editor runs its own server. You can customize the port, but again, you cant run the reverse proxy.

I had the idea of using a PHP or Python CGI script as an intermediary. Something like:

www.mydomain/mydirectory/middleman.py

from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse, json
# hpyothetical apache api
import apache

parsed_path = urlparse.urlparse(self.path)

response = apache(url=parsed_path, port=8080)

sendStuffBack(response)

Would this be possible with Apache? How would I implement it?

Edit: Here is what I did based on @grawity's answer.

helloflask.py

#!/usr/bin/env python

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

middle.py

#!/usr/bin/env python

print ("Content-Type: text/html")
print()

import requests
#response = requests.get("http://localhost:5000")
response = requests.get("http://localhost:8888/token=8a387fe88d662e2568f9b8ec2398191452492e7184536670")

print(response.text)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your Python project is a reverse proxy, and the API you're looking for is just ordinary HTTP. (After all, that's how web browsers interact with Apache already...)

To make HTTP requests, you need a client like urllib or requests:

import requests

response = requests.get("http://" + apache_host + ":8080/" + parsed_path)

By default, all your apps and microservers will think that all clients come from localhost. If that's a problem, see if your apps accept the X-Forwarded-For header. (If they do, include it in all your requests.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...