systemctl设置简单的python项目开机自启
前言:把重复的工作简单化,因为工作的时候每次都要根据id去登录数据库查看其所属的地区,比较繁琐,手机查询也比件麻烦,所以心血来潮做了个简单的前端页面来查询,利用systemctl来控制开机自启。
目录结构:
[root@localhost ~]# tree rfid_query_app rfid_query_app ├── backend │ ├── app.py │ ├── database.py │ ├── __pycache__ │ │ └── database.cpython-39.pyc │ └── requirements.txt └── frontend ├── index.html ├── package-lock.json ├── script.js └── style.css 3 directories, 8 files
前端代码:
[root@localhost ~]# cat rfid_query_app/frontend/index.html
RFID 查询系统
[root@localhost ~]# cat rfid_query_app/frontend/package-lock.json
{ "name": "frontend", "lockfileVersion": 2, "requires": true, "packages": {} }
XXXX1修改成你要查的字段的别名,XXXX2跟的是你要查看的结果的字段名称:
[root@localhost ~]# cat rfid_query_app/frontend/script.js
document.getElementById('rfid-form').addEventListener('submit', async function(event) { event.preventDefault(); const rfid = document.getElementById('rfid').value; const resultDiv = document.getElementById('result'); resultDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 查询中...'; try { const response = await fetch(`/query?rfid=${rfid}`); const data = await response.json(); if (response.ok) { resultDiv.innerHTML = `
`; } else { resultDiv.innerHTML = ` 错误: ${data.error}`; } } catch (error) { resultDiv.innerHTML = ` 查询失败: ${error.message}`; } });
[root@localhost ~]# cat rfid_query_app/frontend/style.css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap'); body { font-family: 'Roboto', sans-serif; background: linear-gradient(to right, #6a11cb, #2575fc); margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; } .container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); width: 90%; max-width: 400px; text-align: center; } h1 { margin-bottom: 20px; color: #333; font-size: 24px; display: flex; align-items: center; justify-content: center; gap: 10px; } form { display: flex; flex-direction: column; gap: 15px; } label { font-size: 16px; color: #555; text-align: left; } .input-container { position: relative; display: flex; align-items: center; } .input-container i { position: absolute; left: 10px; color: #aaa; } input[type="text"] { width: 100%; padding: 10px 10px 10px 30px; font-size: 16px; border: 1px solid #ddd; border-radius: 4px; transition: border-color 0.3s; } input[type="text"]:focus { border-color: #007bff; outline: none; } button { padding: 10px; font-size: 16px; background: linear-gradient(to right, #6a11cb, #2575fc); color: white; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s, transform 0.3s; display: flex; align-items: center; justify-content: center; gap: 5px; } button:hover { background: linear-gradient(to right, #2575fc, #6a11cb); transform: scale(1.05); } #result { margin-top: 20px; font-size: 16px; color: #333; text-align: left; } .result-item { display: flex; justify-content: space-between; padding: 5px 0; }
后端代码:
[root@localhost ~]# cat rfid_query_app/backend/app.py
from flask import Flask, request, jsonify, send_from_directory from database import query_rfid import os app = Flask(__name__, static_folder='../frontend', static_url_path='') @app.route('/') def index(): return send_from_directory(app.static_folder, 'index.html') @app.route('/query', methods=['GET']) def query(): rfid = request.args.get('rfid') result = query_rfid(rfid) return jsonify(result) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
注意替换成自己的数据库配置,sql语句也可视需求进行更改:
[root@localhost ~]# cat rfid_query_app/backend/database.py
import mysql.connector def get_db_connection(): connection = mysql.connector.connect( host='10.220.180.110', port='3306', user='root', password='Yunye+001', database='test' ) return connection def query_rfid(rfid): connection = get_db_connection() cursor = connection.cursor(dictionary=True) query = """ SELECT t1.XXXX2, t1.XXXX2, t1.XXXX2, t2.XXXX2 FROM 表名1 t1 LEFT JOIN 表名2 t2 ON t1.XXXX2 = t2.XXXX2 WHERE t1.XXXX2 = %s ORDER BY t1.production_time DESC LIMIT 1; """ cursor.execute(query, (rfid,)) result = cursor.fetchone() cursor.close() connection.close() return result
运行试一下:
[root@localhost ~]# python rfid_query_app/backend/app.py * Serving Flask app 'app' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on all addresses (0.0.0.0) * Running on http://127.0.0.1:5000 * Running on http://10.220.180.110:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 103-378-621
浏览器访问:http://10.220.180.110:5000
添加到systemctl服务里面(注意路径):
[root@localhost ~]# cat /etc/systemd/system/rfid-cx.service [Unit] Description=RFID Query System After=network.target [Service] User=root Group=root WorkingDirectory=/root/rfid_query_app/backend ExecStart=/usr/bin/python /root/rfid_query_app/backend/app.py Restart=always [Install] WantedBy=multi-user.target
设置开机自启rfid-cx.service:
[root@localhost ~]# systemctl daemon-reload [root@localhost ~]# systemctl enable --now rfid-cx.service Created symlink /etc/systemd/system/multi-user.target.wants/rfid-cx.service → /etc/systemd/system/rfid-cx.service. [root@localhost ~]# systemctl status rfid-cx.service ● rfid-cx.service - RFID Query System Loaded: loaded (/etc/systemd/system/rfid-cx.service; enabled; preset: disabled) Active: active (running) since Wed 2024-07-10 17:49:19 CST; 13s ago Main PID: 277899 (python) Tasks: 3 (limit: 22812) Memory: 43.2M CPU: 362ms CGroup: /system.slice/rfid-cx.service ├─277899 /usr/bin/python /root/rfid_query_app/backend/app.py └─277900 /usr/bin/python /root/rfid_query_app/backend/app.py 7月 10 17:49:19 localhost.localdomain python[277899]: * Serving Flask app 'app' 7月 10 17:49:19 localhost.localdomain python[277899]: * Debug mode: on 7月 10 17:49:19 localhost.localdomain python[277899]: WARNING: This is a development server. Do not use it in a production deployment. Use a production> 7月 10 17:49:19 localhost.localdomain python[277899]: * Running on all addresses (0.0.0.0) 7月 10 17:49:19 localhost.localdomain python[277899]: * Running on http://127.0.0.1:5000 7月 10 17:49:19 localhost.localdomain python[277899]: * Running on http://10.220.180.110:5000 7月 10 17:49:19 localhost.localdomain python[277899]: Press CTRL+C to quit 7月 10 17:49:19 localhost.localdomain python[277899]: * Restarting with stat 7月 10 17:49:19 localhost.localdomain python[277900]: * Debugger is active! 7月 10 17:49:19 localhost.localdomain python[277900]: * Debugger PIN: 858-647-424