并行任务进度监控
import psycopg2 as pg
def doDB(sql,flag):
conn = pg.connect(database="i_twin", user="postgres", password="123456", host="192.168.1.96",
port="5432")
cur = conn.cursor()
cur.execute(sql)
if flag==1:conn.commit()
if flag==2:res = cur.fetchall()
cur.close()
conn.close()
if flag==2:return res
import socket
hostname = socket.gethostname()
print(hostname)
ip = socket.gethostbyname(hostname)
print(ip)
import random
import time
import threading
import os
def st(x):
print('do',x)
c=random.random()*30
time.sleep(c)
print('done',x)
s="select * from z_sch where id='%s' "%(id)
info=doDB(s,2)[0]
s="update z_sch set susnum=%s,sch=%s,updatetime=%s where id='%s' "\
%(info[4]+1,(info[4]+1)/info[3],round(time.time()),id)
doDB(s,1)
id='3'
num=4
t=round(time.time())
s="insert into z_sch values ('%s',%s,'%s',%s,%s,%s,'%s',%s,%s) "%(id,os.getpid(),ip,num,0,0,'执行中',t,t)
doDB(s,1)
threads = []
for x in range(num):
thread = threading.Thread(target=st, args=(x,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
s="update z_sch set state='完成' where id='%s' "%(id)
doDB(s,1)
print('Main end')
python接口服务
可以用自带的http.server,nohup python -m http.server 8001 &,http://192.168.6.103:8001/,不过不方便,支持不够(Unsupported method),更好的有wsgi server和wsgi application fastapi+uvicorn,wsgiref(麻烦) 可以用django、flask
通信数据包的传输、协议的设计,socket、restful restful规范:get请求数据、post新增数据、put更新数据、delete删除数据 接口没什么特别的规范,能交互、稳定就是好接口
import os
import flask, json
from flask import request
server = flask.Flask(__name__)
@server.route('/get', methods=['get'])
def doget():
try:
with open(os.path.dirname(__file__)+'a.json') as f:
data=json.load(f)
print('get data',data)
return data
except FileNotFoundError:
return {'data':None}
@server.route('/post1', methods=[ 'post'])
def dopost1():
a=request.data
if a==b'':return {'no data': 200}
a=json.loads(a)
print('asd',a,type(a))
if a == dict(): return {'data': None}
id=a['id']
print(id)
with open(os.path.dirname(__file__)+'\\'+id+'.json','w') as f:
json.dump(a,f)
print(os.path.dirname(__file__))
print('write sus')
os.system('python cc.py '+id)
with open(os.path.dirname(__file__)+'\\'+id+'end.json') as f:
data=json.load(f)
print(data)
return json.dumps(data)
@server.route('/post2', methods=[ 'post'])
def dopost2():
a=request.data
if a==b'':return {'no data': 200}
a=json.loads(a)
print('asd',a,type(a))
if a == dict(): return {'data': None}
id=a['id']
print(id)
with open(os.path.dirname(__file__)+'\\'+id+'.json','w') as f:
json.dump(a,f)
print(os.path.dirname(__file__))
print('write sus')
os.system('python cc.py '+id)
return {'suc sent data':200}
if __name__ == '__main__':
server.run(debug=True, port=8888, host='0.0.0.0')
import requests
import json
url1='http://192.168.150.30:8888/get'
url2='http://192.168.150.30:8888/post2'
ddd={'a':[2,3],12:'zz',22:[3,2,1,2],'id':'asd2'}
a=requests.post(url2,json.dumps(ddd))
print(a)
print(a.text)
b=requests.get(url1)
bv=b.json()
print(b)
print(bv,type(bv))
|