python脚本 环境准备

现在的公司用 Python 做 Web 开发,入职到现在为止(三个月),算是入门了 Python Web 开发

但是 Python 本身是脚本语言,我还从来没有体会到脚本语言能给日常工作带来的便利

就在昨天下午,我开发一个功能,因为有一些 bug,需要不断的调试,而调试意味着要准备环境,做各种操作,比如删除数据库数据、删除文件、发起 Post 请求等

那时我就在想,这些重复工作,不是正好可以用 Python 这个脚本语言帮我完成吗?

于是就开动了,经过一番查阅资料之后,写出了代码如下,可以一键完成各种准备工作:

 1 # -*- coding=utf-8 -*-
 2 
 3 import os
 4 import pymysql
 5 import requests
 6 import json
 7 
 8 # 删除ok_file文件
 9 def delete_file() :
10     ok_file = os.path.join("/demo/2019-07-15/test.ok")
11     ok_file = ok_file.replace('\', '/')
12     if os.path.exists(ok_file):
13         os.remove(ok_file)
14 
15 
16 # 删除数据库数据
17 def delete_data():
18     # 创建连接
19     conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='test')
20     # 第二种创建连接方式
21     # 连接配置信息
22     # config = {
23     #     'host': '127.0.0.1',
24     #     'port': 3306,
25     #     'user': 'root',
26     #     'password': '123',
27     #     'db': 't1',
28     #     'charset': 'utf8mb4',
29     #     'cursorclass': pymysql.cursors.DictCursor,
30     # }
31     # 创建连接 (2)
32     # connection = pymysql.connect(**config)
33     # 创建游标
34     cursor = conn.cursor()
35     # 执行SQL,并返回收影响行数
36     effect_row = cursor.execute("delete from task_info")
37     # 执行SQL,并返回受影响行数
38     # effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
39     # 执行SQL,并返回受影响行数
40     # effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
41     # 提交,不然无法保存新建或者修改的数据
42     conn.commit()
43     # 关闭游标
44     cursor.close()
45     # 关闭连接
46     conn.close()
47 
48 # 参考: https://www.cnblogs.com/yourstars/p/8196054.html
49 # 发起post请求
50 def launch_post():
51     url = 'http://127.0.0.1:8000/task/'
52     body = {"demo_dirs": ["2019-07-15"]}
53     headers = {'content-type': "application/json"}
54     # print type(body)
55     # print type(json.dumps(body))
56     # 这里有个细节,如果body需要json形式的话,需要做处理
57     # 可以是data = json.dumps(body)
58     response = requests.post(url, data=json.dumps(body), headers=headers)
59     # 也可以直接将data字段换成json字段,2.4.3版本之后支持
60     # response  = requests.post(url, json = body, headers = headers)
61     # 返回信息
62     print(response.text)
63     # 返回响应头
64     print(response.status_code)
65 
66 
67 delete_file() # 删除ok_file文件
68 delete_data() # 删除数据库数据
69 launch_post() # 发起post请求

参考:

https://www.cnblogs.com/jl-bai/p/6124088.html

https://www.cnblogs.com/yourstars/p/8196054.html

原文地址:https://www.cnblogs.com/stone94/p/11205340.html