PyCharm连接linux服务器,且每次按Ctrl+S后就自动同步代码:
①tools:Deployment→Configuration:+→比如hello,SFTP;
②选项卡Connection:host如http://httpbin.org,User name保持默认的root,Password如1~6;③选项卡Mappings:LocalPath填入要上传的项目文件夹,后俩path都填/;
④tools:Deployment→Options:Upload下拉框选择On…Ctrl+S
****************************************分割线****************************************
一句代码搭建服务器:
①目标文件夹如www下进入cmd→python -m http.server --cgi 7788;
②同网段的电脑用浏览器输入本机IP(可ipconfig查询):7788,即可查看www目录结构(若有index.html文件,则默认打开它)。若上句代码用的是默认端口80,则浏览器端可不写【:80】。
③若www内有cgi-bin文件夹,其内有Python文件如test.py,用浏览器如本机的输入网址http://localhost:7788/cgi-bin/test.py,可运行此Python文件。
test.py的内容:
html='''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
<title>服务器</title>
</head>
<body>
<h1>hello,世界</h1>
</body>
</html>
'''
print(html)
****************************************分割线****************************************
flask之签名设计:
flask之签名设计.py:
import requests
from bs4 import BeautifulSoup
from flask import Flask,render_template,request
indexUrl='http://www.uustv.com/'
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def index():
if request.method=='GET':
return render_template('index之签名设计.html')
word=request.form.get('word')
sizes=request.form.get('sizes')
fonts=request.form.get('fonts')
fontcolor=request.form.get('fontcolor')
data=dict(word=word,sizes=sizes,fonts=fonts,fontcolor=fontcolor)
html=requests.post(indexUrl,data=data).text
soup=BeautifulSoup(html,'lxml')
imgUrl=indexUrl+soup.select('.tu > img')[0]['src']
context=dict(imgUrl=imgUrl,word=word,fonts=fonts)
return render_template('index之签名设计.html',**context)
if __name__ == '__main__':
app.run(debug=True,port=80)
**********************分割线**********************
注:早期我用某浪写blog,那里不支持书写html格式,故把半角的<替换为了全角的<
templates文件夹下的——index之签名设计.html:
<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>签名设计</title></head>
<body><div style="text-align:center;line-height:200px">
<form method="post">
输入名字:<input type="word" name="word" value="{{ word|default('') }}">
<select name="sizes" style="display:none;"><option value="60">60</option></select>
样式:<select name="fonts" id="fonts">
<option value="jfcs.ttf">个性签</option>
<option value="bzcs.ttf" >潇洒签</option>
<option value="zql.ttf" >商务签</option>
<option value="yqk.ttf" >可爱签</option>
</select>
<script>$("#fonts option[text='可爱签']").attr("selected", true);</script>
<script>$("#fonts").val("{{ fonts|default("yqk.ttf") }}");</script>
<input name="fontcolor" value="#000000" style="display:none;">
<input type="submit" value="设计" />
</form>
<img src="{{ imgUrl|default('http://www.uustv.com/1.gif') }}">
</div></body>
</html>
****************************************分割线****************************************
flask之酷我音乐:
flask之酷我音乐.py:
import requests
from fake_useragent import UserAgent
def downLoadKuwo(url):
musicID=url.split('?')[0].split('/')[-1]
h={'User-Agent':UserAgent().random}
return requests.get(f'http://antiserver.kuwo.cn/anti.s?format=aac|mp3\
&rid=MUSIC_{musicID}&type=convert_url&response=res',headers=h).url
from flask import Flask,render_template,request,redirect
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def index():
if request.method=='GET':
return render_template('flask之酷我音乐.html')
url=request.form['url']
if not url:
return '需要先填写url,才能下载哦'
downUrl=downLoadKuwo(url)
if not downUrl:
return '输入的载网址不对,应形如:www.kuwo.cn/yinyue/97881'
return redirect(downUrl)
if __name__ == '__main__':
app.run(debug=True) #host='0.0.0.0',port=5001
**********************分割线**********************
templates文件夹下的——flask之酷我音乐.html:(body中的部分)
<form action="/" method="post">
搜索格式:来自百度,如:http://bd.kuwo.cn/yinyue/7746750<br>
或直接在酷我搜索的,如:www.kuwo.cn/yinyue/97881<br>
<br>
<input type="text" name="url" style="width: 400px" >
<input type="submit" value="百度一下">
</form>
****************************************分割线****************************************
把【斗图啦】的图片展示在自己的网站上:
1、把图片数据爬到mySql数据库:爬虫.py
import requests,re,pymysql
from fake_useragent import UserAgent
conn=pymysql.connect(host='localhost',port=3306,user='斗图啦',password='',
db='斗图啦',charset='utf8')
cur=conn.cursor()
reg=re.compile('data-original="(.*?)".*?alt="(.*?)"',re.S)
for page in range(1,1084):
print('正在下载第%s页' %page)
url='http://www.doutula.com/photo/list/?page=%s' %page
h={'User-Agent':UserAgent().random}
response=requests.get(url,headers=h).text
results=reg.findall(response)
for image in results:
if len(image[1])<50: #字太多的图不要
cur.execute('insert into image(name,imageUrl) values("%s","%s")' %(image[::-1]))
conn.commit()
cur.close()
conn.close()
**********************分割线**********************
2、flask之斗图啦.py:
from flask import Flask,request,render_template
import pymysql,random
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index之斗图啦.html')
@app.route('/search')
def search():
kw=request.args['kw'] #取PostData或网址?后某参数的值,POST用form,GET用args
count=request.args['count']
#SQL语句中,like对regexp:_对.,%对.*
#查询的多行记录:django是[{},{}];flask默认却是[(),()],不方便html调用,连库时要改cursorclass
# cur.execute('select * from image where name like "%{}%" limit 1000'.format(kw))
cur.execute('select * from image where name regexp ".*%s.*" limit 1000' %kw)
data=cur.fetchmany(int(count))
random.shuffle(data)
return render_template('index之斗图啦.html',images=data)
if __name__ == '__main__':
conn = pymysql.connect(host='localhost', port=3306, user='斗图啦', password='',
db='斗图啦', charset='utf8',cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()
app.run(debug=True)
**********************分割线**********************
3、index之斗图啦.html:(body中的部分)
<form action="/search" method="get">
搜索内容:<input type="text" name="kw" style="width: 240px"><br>
展示数量:<input type="text" name="count" value="10">
<input type="submit" value="查询">
</form>
{% for image in images %}
<img src="{{image.imageUrl}}" alt="{{image.name}}"> <!--改为DictCursor的目的所在-->
{% endfor %}
****************************************分割线****************************************
制作名片二维码:
flask之名片二维码.py,文件夹templates和static,都在同一目录下
1、flask之名片二维码.py:
from flask import Flask,request,render_template
import qrcode
def code(form):
t=form['name'],form.get('company'),form.get('title'),form.get('address'),\
form.get('mobile'),form.get('email'),form.get('url'),form.get('note')
qr=qrcode.QRCode(version=1,box_size=4,border=2,
error_correction=qrcode.ERROR_CORRECT_Q) #容错范围25%
qr.add_data('''BEGIN:VCARD\nVERSION:3.0\n
FN:{}\nORG:{}\n
TITLE:{}\nADD;WORK:{}\n
TEL;WORK:{}\nEMAIL;WORK:{}\n
URL:{}\nNOTE:{}\n
END:VCARD'''.format(*t))
path='static/CardImg/%s.png' %','.join(t[:4]) #取前4条做二维码图片名
qr.make_image().save(path)
return path
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def index():
if request.method=='GET':
return render_template('index之名片二维码.html')
form=request.form #若取Get请求的各参数,则是request.args
path=code(form)
context={'path':path,'info':path.split('/')[-1]}
return render_template('index之名片二维码.html',**context)
if __name__ == '__main__':
app.run(debug=True,host='127.0.0.1',port=5000)
**********************分割线**********************
2、index之名片二维码.html:(body中的部分)
<form action="/" method="post">
姓名:<input type="text" name="name" style="width: 150px">
公司:<input type="text" name="company" style="width: 150px"><br>
职位:<input type="text" name="title" style="width: 150px">
地址:<input type="text" name="address" style="width: 150px"><br>
手机:<input type="text" name="mobile" style="width: 150px">
邮箱:<input type="text" name="email" style="width: 150px"><br>
主页:<input type="text" name="url" style="width: 150px">
备注:<input type="text" name="note" style="width: 150px"><br>
<input type="submit" value="生成二维码"><br>
</form>
<img src="{{path}}" alt="{{info}}">
****************************************分割线****************************************
转自:潭州学院李天强
二维码:
from flask import Flask,request,render_template
import qrcode,time
app=Flask(__name__,template_folder=r'E:\pTest\templates')
def codeUrl(img):
# 图片等资源的路径要以static开头,新生成文件所在的各层文件夹要提前建好
path='static/CodeImg/%s.png' %time.time()
img.save(path)
return render_template('img.html',codeImg=path)
@app.route('/hello')
def chengy():
return 'hello world'
@app.route('/')
def index():
return render_template('url.html')
@app.route('/url',methods=['Get','Post'])
def url():
if request.method=='GET': #用了==,则全部大写
return '当前为GET请求'
httpUrl=request.form.get('text') #Post请求用form方法,Get用args
img=qrcode.make(httpUrl)
return codeUrl(img) #此处也要有return:return render_template……
@app.route('/text',methods=['Get','Post'])
def text():
if request.method=='GET':
return render_template('text.html')
text=request.form.get('text')
if len(text)<=1108:
img=qrcode.make(text)
return codeUrl(img)
txt='static/codeFile/%s.txt' %time.time()
with open(txt,'w',encoding='utf-8') as f:
f.write(text)
img=qrcode.make('http://127.0.0.1:5000/%s' %txt)
return codeUrl(img)
if __name__ == '__main__':
app.debug=True
app.run()
**************************分割线**************************
templates下的3个html模板:
1、url.html:
<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>网址生成二维码</title></head>
<body><form action="/url" method="post">
url:<input type="text" name="text" value="https://www.x.com/" style="width: 240px">
<input type="submit" value="生成">
</form></body>
</html>
**********************分割线**********************
2、text.html:
<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>文字生成二维码</title></head>
<body><form action="/text" method="post">
请输入文字:<textarea name="text" id="" cols="30" rows="10"></textarea>
<input type="submit" value="生成">
</form></body>
</html>
**********************分割线**********************
3、img.html:
<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>二维码图片</title></head>
<body><img src="{{codeImg}}" alt=""></body>
</html>
****************************************分割线****************************************网盘:
网页端的网盘.py:
from flask import Flask,render_template,request
app=Flask(__name__)
@app.route('/')
def index():
context={'name':'上传文件'}
return render_template('index.html',**context)
@app.route('/upload',methods=['POST'])
def upload():
file=request.files.get('file')
if not file:
return '请先选择文件再上传'
file.save('static/%s' %file.filename) #static是根目录,前面不能加/
return 'http://127.0.0.1:5000/static/%s' %file.filename
if __name__ == '__main__':
app.run(debug=True)
**********************分割线**********************
index.html:(body中的部分)
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="{{name}}">
</form>
**********************分割线**********************
app客户端的网盘.py:
from tkinter import *
from tkinter.filedialog import *
import requests,urllib
def upload():
filename= askopenfilename(title='选择文件')
fileUpload=open(filename,'rb').read()
#复制F12看到的data,存放二进制数据的俩空行也不能省略
data='''------WebKitFormBoundarysGPHg93Da3yvEPAa
Content-Disposition: form-data; name="file"; filename="%s"
Content-Type: application/octet-stream
[file]
------WebKitFormBoundarysGPHg93Da3yvEPAa--''' %filename.split('/')[-1]
data=bytes(data.encode()).replace(bytes(b'[file]'),fileUpload)
headers={'Content-Type':'multipart/form-data; boundary=----WebKitFormBoundarysGPHg93Da3yvEPAa'}
result=requests.post('http://127.0.0.1:5000/upload',headers=headers,data=data).content
ent.delete(0,END) #清空输入框,防止在原文末尾追加
ent.insert(0,result)
def download():
urllib.request.urlretrieve(ent.get(),asksaveasfilename())
root.quit()
root=Tk()
root.title('网盘')
root.geometry('+800+400') #表示窗体大小的500x600,用的小写英文字母x,不是中文乘号
ent=Entry(root,width=50)
ent.grid()
btnUpload=Button(root,text=' 上 传 ',command=upload)
btnUpload.grid()
btnDownload=Button(root,text=' 下 载 ',command=download)
btnDownload.grid()
root.mainloop()
****************************************分割线****************************************
微信公众号的二次开发:
网友给你的微信公号发个照片,就自动对其回复3样信息——性别、年龄、微笑指数
faceRecognition.py:
import requests
from fake_useragent import UserAgent
def getFaceInfo(image_url):
h={'User-Agent':UserAgent().random}
url='https://api-cn.faceplusplus.com/facepp/v3/detect'
#copy自一网友的face++账号的api_key和api_secret,有效期大概半年
data={'api_key':'RU8VkInUd4zpcCo2GbKxPz90rPoaY5O0',
'api_secret':'01YadiHNX_Fpqw6saBYa2POD6ozL6gWu',
'image_url':image_url,
'return_attributes':'gender,age,smiling'}
r=requests.post(url,data,headers=h).json()['faces'][0]['attributes']
gender=r['gender']['value'];age=r['age']['value'];smile=r['smile']['value']
return gender,age,smile
if __name__ == '__main__':
print(getFaceInfo('http://img1.gtimg.com/ent/pics/hv1/205/194/2126/138292825.jpg'))
**********************分割线**********************
微信人脸识别.py:
from faceRecognition import getFaceInfo
from xml.etree import ElementTree as et
from flask import Flask,request,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/wx',methods=['GET','POST'])
def winxin(): #强子院长在其微信公号所关联的网址:www.litianqiang.com/wx
if request.method=='GET':
return request.args['echostr'] #get请求取网址尾的参数的值
data=request.get_data() #取正文;此处是网民发了图,微信转义后再post来的图片消息的xml
xml=et.fromstring(data)
ToUserName=xml.findtext('.//ToUserName') #To…指你的微信公号,From则是网民个人号
FromUserName=xml.findtext('.//FromUserName') #xpath定位,或者用正则
CreateTime=xml.findtext('.//CreateTime')
PicUrl=xml.findtext('.//PicUrl') #网民发来的xml是image消息,公号返回他的xml是text消息
gender,age,smile=getFaceInfo(PicUrl)
Content=f'人脸信息如下:\n性别:{gender}\n年龄:{age}\n微笑指数:{smile}'
context={'FromUserName':FromUserName,'ToUserName':ToUserName,
'CreateTime':CreateTime,'Content':Content}
return render_template('index之微信人脸识别.html',**context)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=2346) #用域名而非IP访问,改host为全0
**********************分割线**********************
templates文件夹下的index之微信人脸识别.html
<xml>
<ToUserName><![CDATA[{{ FromUserName }}]]></ToUserName>
<FromUserName><![CDATA[{{ ToUserName }}]]></FromUserName>
<CreateTime>{{ CreateTime }}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{{ Content }}]]></Content>
</xml>