第6課:datetime模組、操作資料庫、__name__、redis、mock介面

來源:互聯網
上載者:User

標籤:date   成功   into   插入資料   l資料庫   檔案匯入   串連   時間   server   

1.  datetime模組
import datetimeprint(datetime.datetime.today())  # 目前時間 2018-01-23 17:22:35.739667print(datetime.datetime.now())  # 和today一樣 2018-01-23 17:22:35.739667print(datetime.datetime.today().strftime(‘%H:%M:%S‘))  # 按指定格式格式化好的時間字串print(datetime.datetime.today() + datetime.timedelta(-3))  # 取三天前的 三天后的(3) 2018-01-20 17:25:37.470085print(datetime.date.today())  # 取當天的日期 2018-01-23
2. 操作mysql資料庫
import pymysqlimport config# 1. 串連mysql,ip 連接埠號碼 使用者名稱 密碼 資料庫# 2. 建立遊標# 3. 執行sql# 4. 擷取結果# 5. 關閉遊標# 6. 關閉串連# charset必須寫utf8,寫utf-8會報錯conn = pymysql.connect(host=config.host, port=config.port, user=config.user, passwd=config.passwd,                       db=config.dbname, charset=‘utf8‘)cur = conn.cursor()  # 建立遊標,這種方式擷取到的返回結果是元組# cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 這種方式擷取到的結果是字典類型的sql = ‘select * from bt_stu limit 2;‘# sql = "insert into bt_stu values(560, ‘qq‘, 1, 18101000001, ‘中國‘, 1);"cur.execute(sql)  # 執行sqlconn.commit()res = cur.fetchall()  # 擷取sql語句執行的結果,是一個二維的元組# res1 = cur.fetchone()  # 只擷取一條結果,它的結果是一個一維元組print(res)# print(res1)## cur.scroll(0, mode=‘absolute‘)  # 移動遊標,絕對路徑,移至最前面# cur.scroll(0, mode=‘relative‘)  # 移動遊標,相對於當前位置cur.close()conn.close()
3. if __name__ == ‘__main__‘:   # 用法
a.pyprint("outside: ", __name__)  # 別的檔案匯入這個檔案,啟動並執行結果是當前檔案名稱toolsif __name__ == ‘__main__‘:  # 別人匯入這個檔案時,這個函數不執行,    print(‘main:‘, __name__)  # 運行當前檔案時,結果是__main__

  

b.py
# import一個檔案實質是把這個檔案運行了一遍# import的檔案中如果有if __name__ == ‘__main__‘,匯入這個檔案時時不執行這個函數import a# 運行此檔案輸出結果是a
4. redis操作
1.  關係型資料庫:如mysql Oracle sqlserver     
非關係型資料庫:
  key-value格式的
  memcahe # 存在記憶體中
  redis # 存在記憶體中
  mongodb # 資料存在磁碟中
2.   redis的安裝:pip install redis
3.   
import redis# redis 只有密碼,沒有使用者名稱# 字串類型r = redis.Redis(host=‘211.149.***.**‘, port=6379, password=‘******‘, db=1)  # 連接埠預設6379# r.set(‘qxy_session‘, ‘201801211506‘) # set資料# print(r.get(‘qxy_session‘))  # redis取出來的資料都是bytes類型的 b‘201801211506‘# print(r.get(‘qxy_session‘).decode())  # 所以需要用decode方法轉成字串 201801211506# r.delete(‘qxy_session‘)  # 刪除一個# r.setex(‘qxy‘, ‘hahaha‘, 20)  # 可以指定key的失效時間,單位是秒# set get delete setex 都是針對string類型的 k - v# 這種寫法是有層級的r.set(‘qxy:test1‘, ‘沒交作業‘)r.set(‘qxy:test2‘, ‘交了作業‘)print(r.keys())  # 擷取所有的keyprint(r.keys(‘qxy*‘))  # 以txz開頭的keyprint(r.type(‘qxy:test1‘))  # 擷取key的類型# hash類型r.hset(‘qxy_sessions‘, ‘q1‘, ‘1‘)  # 插入資料r.hset(‘qxy_sessions‘, ‘q2‘, ‘2‘)r.hset(‘qxy_sessions‘, ‘q3‘, ‘3‘)print(r.hget(‘qxy_sessions‘, ‘q1‘).decode())  # 擷取某條資料print(r.hgetall(‘qxy_sessions‘))  # 擷取hash類型中所有的類型all_data = {}for k,v in r.hgetall(‘qxy_sessions‘).items():    k = k.decode()    v = v.decode()    all_data[k] = vprint(all_data)# hash類型沒有到期時間

練習題

import redis# 將redis中db1的資料移轉至db8中r = redis.Redis(host=‘211.149.***.**‘, port=6379, password=‘******‘, db=1)r_new = redis.Redis(host=‘211.149.***.**‘, port=6379, password=‘******‘, db=8)for k in r.keys(‘‘):    if r.type(r.keys()) == b‘string‘:  # 或者用decode()        v = r.get(k)        r_new.set(k, v)        print(v.decode())    elif r.type(r.keys()) == b‘hash‘:        keys = r.hgetall(k)        for kk, vv in keys.items():            r_new.hset(k, kk, vv)
5. 開發介面
  1. mock(類比)介面的用處

         1) 暫時代替第三方介面

         2) 輔助測試:用來代替沒有開發好的介面

      3) 查看資料

2. 需先安裝flask模組:pip install flask

import flaskfrom conf import configimport jsonfrom lib.tools import op_mysql# import tools #  tools.op_mysql()# 介面,後台服務server = flask.Flask(__name__)@server.route(‘/get_user‘, methods=[‘get‘, ‘post‘])   # 這句話表示這個函數變身為介面def get_all_user():    sql = ‘select * from users;‘    response = op_mysql(host=config.HOST, user=config.USER, password=config.PASSWORD, db=config.DBNAME, port=config.PORT,                        charset=‘utf8‘, sql=sql)    res = json.dumps(response, ensure_ascii=False, indent=4)    return res@server.route(‘/add_user‘, methods=[‘post‘])def add_users():    user = flask.request.values.get(‘user‘)    passwd = flask.request.values.get(‘passwd‘)    print(user, passwd)    if user and passwd:        sql = "insert into users values(‘%s‘,‘%s‘);" % (user, passwd)        op_mysql(host=config.HOST, user=config.USER, password=config.PASSWORD, db=config.DBNAME, port=config.PORT,                 charset=‘utf8‘, sql=sql)        response = {‘code‘: 200, ‘msg‘: ‘操作成功‘}    else:        response = {‘code‘: 503, ‘msq‘: ‘必填參數未填‘}    return json.dumps(response, ensure_ascii=False)# host=‘0.0.0.0‘ 代表一個區域網路內的所有人都可以訪問;加上debug:不需要重啟服務server.run(port=8888, host=‘0.0.0.0‘, debug=True) 

在postman中訪問這兩個介面

 

第6課:datetime模組、操作資料庫、__name__、redis、mock介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.