如何通过URL(GET查询)访问CentOS7+Nginx环境下的Python脚本并解析数据
Alright, let's walk through this step by step. Since Nginx can't run Python scripts directly, we'll use a WSGI server (like uWSGI) to act as the middleman between Nginx and your script. Here's exactly what you need to do:
1. Install Required Tools
First, make sure you have Python and pip set up, then install uWSGI and a lightweight web framework (I'll use Flask for simplicity—it makes handling GET params a breeze):
# Install pip if you don't have it sudo yum install epel-release sudo yum install python3-pip # Install uWSGI and Flask sudo pip3 install uwsgi flask
2. Update Your Python Script to Handle GET Requests
Modify your existing script to accept and respond to GET queries. Here's a minimal example that integrates Flask (you can adapt this to your existing data generation/print logic):
# save as my_script.py from flask import Flask, request app = Flask(__name__) @app.route('/data', methods=['GET']) def get_data(): # Get query parameters (e.g., ?id=123&filter=active) param1 = request.args.get('param1', default='default_value', type=str) param2 = request.args.get('param2', type=int) # Replace this with your existing data generation/print logic output_data = f"Received param1: {param1}, param2: {param2}" # Return data in a parseable format (JSON is ideal for parsing) return {'data': output_data}, 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
If you don't want to use Flask, you can write a raw WSGI-compliant script, but Flask will save you a ton of boilerplate for handling requests and params.
3. Configure uWSGI
Create a uWSGI configuration file to manage your script. Save this as my_script.ini:
[uwsgi] module = my_script:app master = true processes = 4 socket = /tmp/my_script.sock chmod-socket = 660 vacuum = true die-on-term = true
This tells uWSGI to run your Flask app, create a Unix socket for Nginx to communicate with, and set proper permissions.
4. Set Up a Systemd Service for uWSGI
To make sure uWSGI runs on boot and stays running, create a systemd service file. Save as /etc/systemd/system/my_script.service:
[Unit] Description=uWSGI instance to serve my_script After=network.target [Service] User=your_username Group=nginx WorkingDirectory=/path/to/your/script/directory Environment="PATH=/usr/bin/python3" ExecStart=/usr/local/bin/uwsgi --ini my_script.ini [Install] WantedBy=multi-user.target
Replace your_username and /path/to/your/script/directory with your actual user and script path. Then enable and start the service:
sudo systemctl daemon-reload sudo systemctl start my_script.service sudo systemctl enable my_script.service
5. Configure Nginx to Route Requests
Edit your Nginx config (usually in /etc/nginx/nginx.conf or /etc/nginx/conf.d/your_site.conf) to add a location block that forwards requests to uWSGI:
server { listen 80; server_name your_domain_or_ip; location /data { include uwsgi_params; uwsgi_pass unix:/tmp/my_script.sock; } }
Replace your_domain_or_ip with your server's public IP or domain name. Test the Nginx config and reload:
sudo nginx -t sudo systemctl reload nginx
6. Fix Permissions & Firewall
- SELinux Adjustment: CentOS 7 has SELinux enabled by default, which might block Nginx from accessing the uWSGI socket. Run this to allow it:
sudo setsebool -P httpd_can_network_connect 1 sudo chcon -t httpd_sys_content_t /path/to/your/script/directory - Firewall: Open port 80 to allow external requests:
sudo firewall-cmd --add-service=http --permanent sudo firewall-cmd --reload
7. Test the Endpoint
Now you can access your script via URL with GET params! For example:
http://your_domain_or_ip/data?param1=test¶m2=42
You'll get a JSON response that's easy to parse in any client.
内容的提问来源于stack exchange,提问作者Leeloo

