日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Dataset基于SQLAlchemy的便利工具

數(shù)據(jù)集使得數(shù)據(jù)庫中的數(shù)據(jù)讀取和寫入數(shù)據(jù)就像閱讀和編寫JSON文件一樣簡單。

Dataset對于操作JSON、CSV文件、NoSQL非常好用。

 
 
 
  1. import dataset

連接MySQL數(shù)據(jù)庫:

 
 
 
  1. db = dataset.connect('mysql://username:password@10.10.10.10/ctf?charset=utf8')

用戶名:username,密碼:password,數(shù)據(jù)庫地址(地址+端口):10.10.10.10,database名: ctf

連接SQLite數(shù)據(jù)庫:

 
 
 
  1. db = dataset.connect('sqlite:///ctf.db')

連接PostgreSQL數(shù)據(jù)庫:

 
 
 
  1. db = dataset.connect('postgresql://scott:tiger@localhost:5432/mydatabase')

一定要注意指定字符編碼

 
 
 
  1. table = db['city'] #(選擇city表)
  2. user = table('name') # 找出表中'name'列屬性所有數(shù)據(jù)
  3. res = db.query('select name from table limit 10') # 如果不需要查看全部數(shù)據(jù)的話***用limit,因為全部數(shù)據(jù)的載入非常非常耗時間
  4. for x in res:
  5. print x['name'] # 選name字段的數(shù)據(jù)
  6. table.insert(dict(name='John Doe', age=37))
  7. table.insert(dict(name='Jane Doe', age=34, gender='female'))
  8. john = table.find_one(name='John Doe') 

在數(shù)據(jù)庫中查找是否有同時滿足多個條件的數(shù)據(jù):table.find_one(屬性1=屬性值1, 屬性2=屬性值2, …)

注:find_one速度很慢

插入數(shù)據(jù)

dataset會根據(jù)輸入自動創(chuàng)建表和字段名

 
 
 
  1. table = db['user']
  2. # 或者table = db.get_table('user')
  3. table.insert(dict(name='John Doe', age=46, country='China'))
  4. table.insert(dict(name='Jane Doe', age=37, country='France', gender='female'))
  5. # 主鍵id自動生成 

更新數(shù)據(jù)

 
 
 
  1. table.update(dict(name='John Doe', age=47), ['name'])
  2. # 第二個參數(shù)相當(dāng)于sql update語句中的where,用來過濾出需要更新的記錄 

事務(wù)操作

事務(wù)操作可以簡單的使用上下文管理器來實現(xiàn),出現(xiàn)異常,將會回滾

 
 
 
  1. with dataset.connect() as tx:
  2. tx['user'].insert(dict(name='John Doe', age=46, country='China'))
  3. # 相當(dāng)于:
  4. db = dataset.connect()
  5. db.begin()
  6. try:
  7. db['user'].insert(dict(name='John Doe', age=46, country='China'))
  8. db.commit()
  9. except:
  10. db.rollback()
  11. # 也可以嵌套使用:
  12. db = dataset.connect()
  13. with db as tx1:
  14. tx1['user'].insert(dict(name='John Doe', age=46, country='China'))
  15. with db as tx2:
  16. tx2['user'].insert(dict(name='Jane Doe', age=37, country='France', gender='female')) 

從表獲取數(shù)據(jù)

 
 
 
  1. users = db['user'].all()
  2. for user in db['user']:
  3. # print(user['age'])
  4. # chinese_users = user.find(country='China')
  5. john = user.find_one(name='John Doe') 

獲取非重復(fù)數(shù)據(jù)

 
 
 
  1. db['user'].distinct('country')

刪除記錄

 
 
 
  1. table.delete(place='Berlin')

執(zhí)行SQL語句

 
 
 
  1. result = db.query('SELECT country, COUNT(*) c FROM user GROUP BY country')
  2. for row in result:
  3. print(row['country'], row['c']) 

導(dǎo)出數(shù)據(jù)

 
 
 
  1. result = db['users'].all()
  2. dataset.freeze(result, format='json', filename='users.json') 

JSON

JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,非常易于人閱讀和編寫。

 
 
 
  1. import json

json.dumps 將 Python 對象編碼成 JSON 字符串

json.loads 將已編碼的 JSON 字符串解碼為 Python 對象

MySQL數(shù)據(jù)庫:

分類表-categories,包括類別web,reversing,crypto(加解密),mic等

題目表-tasks,包括題目id,題目名,flag,分值,文件&地址,題目等級,題目詳細(xì)描述

flag表-flag,包括題目id,用戶id,得分,時間戳

用戶表-users,包括用戶id,用戶名,密碼

題目分類表-cat_task,包括題目id,題目類別id

flag表中每條數(shù)據(jù)由于是有題目ID task_id和用戶ID user_id來共同確認(rèn)的,所以采用復(fù)合主鍵:primary key (task_id,user_id)

聯(lián)合主鍵和復(fù)合主鍵的區(qū)別

python裝飾器

Decorator通過返回包裝對象實現(xiàn)間接調(diào)用,以此插入額外邏輯

https://www.zhihu.com/question/26930016

wraps本身也是一個裝飾器,它能把原函數(shù)的元信息拷貝到裝飾器函數(shù)中,這使得裝飾器函數(shù)也有和原函數(shù)一樣的元信息了

 
 
 
  1. from functools import wraps
  2. def logged(func):
  3. @wraps(func)
  4. def with_logging(*args,**kwargs):
  5. print func.__name__ + "was called"
  6. return func(*args,**kwargs)
  7. return with_logging
  8.  
  9. @logged
  10. def f(x):
  11. """does some math"""
  12. return x + x * x
  13.  
  14. print f.__name__ # prints 'f'
  15. print f.__doc__ # prints 'does some math' 

web框架采用flask

 
 
 
  1. from flask import Flask

引入Flask類,F(xiàn)lask類實現(xiàn)了一個WSGI(Web Server Gateway Interface)應(yīng)用

 
 
 
  1. app = Flask(__name__)

app是Flask的實例,它接收包或者模塊的名字作為參數(shù),但一般都是傳遞__name__

 
 
 
  1. @app.route('/')
  2. def hello_world():
  3. return 'Hello World!' 

使用app.route裝飾器會將URL和執(zhí)行的視圖函數(shù)的關(guān)系保存到app.url_map屬性上。處理URL和視圖函數(shù)的關(guān)系的程序就是路由,這里的視圖函數(shù)就是hello_world

 
 
 
  1. if __name__ == '__main__':
  2. app.run(host='0.0.0.0',port=9000) 

使用這個判斷可以保證當(dāng)其他文件引用這個文件的時候(例如from hello import app)不會執(zhí)行這個判斷內(nèi)的代碼,也就是不會執(zhí)行app.run函數(shù)。

執(zhí)行app.run就可以啟動服務(wù)了。默認(rèn)Flask只監(jiān)聽虛擬機(jī)的本地127.0.0.1這個地址,端口為5000。而我們對虛擬機(jī)做的端口轉(zhuǎn)發(fā)端口是9000,所以需要制定host和port參數(shù),0.0.0.0表示監(jiān)聽所有地址,這樣就可以在本機(jī)訪問了。

服務(wù)器啟動后,會調(diào)用werkzeug.serving.run_simple進(jìn)入輪詢,默認(rèn)使用單進(jìn)程單線程的werkzeug.serving.BaseWSGIServer處理請求,實際上還是使用標(biāo)準(zhǔn)庫BaseHTTPServer.HTTPServer,通過select.select做0.5秒的while TRUE的事件輪詢。當(dāng)我們訪問http://127.0.0.1:9000/,通過app.url_map找到注冊的/這個URL模式,就找到了對應(yīng)的hello_world函數(shù)執(zhí)行,返回hello world!,狀態(tài)碼為200。如果訪問一個不存在的路徑,如訪問http://127.0.0.1:9000/a,Flask找不到對應(yīng)的模式,就會向瀏覽器返回Not Found,狀態(tài)碼為404

flask中jsonify的作用

jsonify的作用實際上就是將我們傳入的json形式數(shù)據(jù)序列化成為json字符串,作為響應(yīng)的body,并且設(shè)置響應(yīng)的Content-Type為application/json,構(gòu)造出響應(yīng)返回至客戶端

效果等于json.dumps

jsonify的Content-Type字段值為application/json

json.dumps的Content-Type字段值為text/html

修改flask中靜態(tài)文件夾

修改的flask默認(rèn)的static文件夾只需要在創(chuàng)建Flask實例的時候,把static_folder和static_url_path參數(shù)設(shè)置為空字符串即可。

app = Flask(__name__, static_folder=”, static_url_path=”)

訪問的時候用url_for函數(shù),res文件夾和static文件夾同一級:

url_for(‘static’, filename=’res/favicon.ico’)

werkzeug

werkzeug是一個WSGI工具包,可以作為一個Web框架的底層庫。它封裝好了很多Web框架的東西,例如 Request,Response等等。Flask框架就是一Werkzeug 為基礎(chǔ)開發(fā)的

generate_password_hash(password)

將用戶輸入的明文密碼加密成密文進(jìn)行存儲

密碼加鹽哈希函數(shù)。用來將明文密碼加密,返回加密后的密文,用來進(jìn)行用戶注冊

函數(shù)定義:

werkzeug.security.generate_password_hash(password, method='pbkdf2:sha1', salt_length=8)

密文格式:method$salt$hash

password: 明文密碼

method: 哈希的方式(需要是hashlib庫支持的),格式為

pbpdf2:[:iterations]。參數(shù)說明:

method:哈希的方式,一般為SHA1,

iterations:(可選參數(shù))迭代次數(shù),默認(rèn)為1000。

slat_length: 鹽值的長度,默認(rèn)為8

check_password_hash(hash,password)

驗證經(jīng)過generate_password_hash哈希的密碼,將明文和密文進(jìn)行比較,查看是否一致,用來驗證用戶登錄

函數(shù)定義:

werkzeug.security.check_password_hash(pwhash, password)

pwhash: generate_password_hash生成的哈希字符串

password: 需要驗證的明文密碼

flask中的session

 
 
 
  1. rom flask import session
  2. user = db['users'].find_one(username=username)
  3. session['user_id'] = user['id'] 

由于使用了session,所以需要設(shè)置一個secret_key用來做一些模塊的hash

Flask Web Development 中的內(nèi)容:

SECRET_KEY配置變量是通用密鑰,可在Flask和多個第三方擴(kuò)展中使用。如其名所示,加密的強(qiáng)度取決于變量值的機(jī)密度。不同的程序要使用不同的密鑰,而且要保證其他人不知道你所用的字符串。

SECRET_KEY的作用主要是提供一個值做各種HASH, 是在其加密過程中作為算法的一個參數(shù)(salt或其他)。所以這個值的復(fù)雜度也就影響到了數(shù)據(jù)傳輸和存儲時的復(fù)雜度。

flask 變量規(guī)則

要給URL添加變量部分,你可以把這些特殊的字段標(biāo)記為, 這個部分將會作為命名參數(shù)傳遞到你的函數(shù)。規(guī)則可以用指定一個可選的轉(zhuǎn)換器

 
 
 
  1. @route('/hello/')
  2. def index(name):
  3. return 'Hello {{name}}!' 

數(shù)據(jù)庫查詢

對dataset的數(shù)據(jù)查詢,使用冒號來為變量傳參。

select f.task_id from flags f where f.user_id = :user_id”’,user_id=session[‘user_id’])

模板渲染

使用render_template方法來渲染模板。將模板名和你想作為關(guān)鍵字的參數(shù)傳入模板的變量

MySQL

IFNULL(expr1,expr2)

如果expr1不是NULL,IFNULL()返回expr1,否則它返回expr2。

IFNULL()返回一個數(shù)字或字符串值,取決于它被使用的上下文環(huán)境。

max函數(shù)是用來找出記錄集中***值的記錄

  1. 對于left join,不管on后面跟什么條件,左表的數(shù)據(jù)全部查出來,因此要想過濾需把條件放到where后面
  2. 對于inner join,滿足on后面的條件表的數(shù)據(jù)才能查出,可以起到過濾作用。也可以把條件放到where后面

在使用left jion時,on和where條件的區(qū)別如下:

  1. on條件是在生成臨時表時使用的條件,它不管on中的條件是否為真,都會返回左邊表中的記錄。
  2. where條件是在臨時表生成好后,再對臨時表進(jìn)行過濾的條件。這時已經(jīng)沒有l(wèi)eft join的含義(必須返回左邊表的記錄)了,條件不為真的就全部過濾掉。

order by的用法 

使用order by,一般是用來,依照查詢結(jié)果的某一列(或多列)屬性,進(jìn)行排序(升序:ASC;降序:DESC;默認(rèn)為升序)。

當(dāng)排序列含空值時:

ASC:排序列為空值的元組***顯示。

DESC:排序列為空值的元組***顯示。

可以把null值看做無窮大

select * from s order by sno desc, sage asc

group by的用法

group by按照查詢結(jié)果集中的某一列(或多列),進(jìn)行分組,值相等的為一組

1、細(xì)化集函數(shù)(count,sum,avg,max,min)的作用對象:

未對查詢結(jié)果分組,集函數(shù)將作用于整個查詢結(jié)果。

對查詢結(jié)果分組后,集函數(shù)將分別作用于每個組。

SELECT cno,count(sno) from sc group by cno

2、GROUP BY子句的作用對象是查詢的中間結(jié)果表

分組方法:按指定的一列或多列值分組,值相等的為一組。

使用GROUP BY子句后,SELECT子句的列名列表中只能出現(xiàn)分組屬性(比如:sno)和集函數(shù)(比如:count())

select sno,count(cno) from sc group by sno

3、多個列屬性進(jìn)行分組

select cno,grade,count(cno) from sc group by cno,grade

4、使用HAVING短語篩選最終輸出結(jié)果

只有滿足HAVING短語指定條件的組才輸出。

HAVING短語與WHERE子句的區(qū)別:作用對象不同。

1、WHERE子句作用于基表或視圖,從中選擇滿足條件的元組。

2、HAVING短語作用于組,從中選擇滿足條件的組

select sno from sc group by sno having count(cno)>3

select sno,count(cno) from sc where grade>60 group by sno having count(cno)>3

MySQL的左連接、右連接、等值連接

1.左連接(left join )

 
 
 
  1. select m.columnname……,n.* columnname…..
  2. from left_table m left join right_table n on m.columnname_join=n.columnname_join and n.columnname=xxx
  3. where m.columnname=xxx….. 

ON是連接條件,用于把2表中等值的記錄連接在一起,但是不影響記錄集的數(shù)量。若是表left_table中的某記錄,無法在表right_table找到對應(yīng)的記錄,則此記錄依然顯示在記錄集中,只是表right_table需要在查詢顯示的列的值用NULL替代;

ON連接條件中表n.columnname=xxx用于控制right_table表是否有符合要求的列值還是用NULL替換的方式顯示在查詢列中,不影響記錄集的數(shù)量;

WHERE字句控制記錄是否符合查詢要求,不符合則過濾掉

2.右連接(right join)

 
 
 
  1. select m.columnname……,n.* columnname…..
  2. from left_table m right join right_table n on m. columnname_join=n. columnname_join and m. columnname=xxx
  3. where n.columnname=xxx….. 

3.等值連接

 
 
 
  1. select m.columnname……,n.* columnname…..
  2. from left_table m [inner] join right_table n on m. columnname_join=n. columnname_join
  3. where m.columnname=xxx….. and n.columnname=xxx…. 

或者

 
 
 
  1. select m.columnname……,n.* columnname…..
  2. from left_table m , right_table n
  3. where m. columnname_join=n. columnname_join and
  4. m.columnname=xxx….. and n.columnname=xxx…. 

ON是連接條件,不再與左連接或右連接的功效一樣,除了作為2表記錄匹配的條件外,還會起到過濾記錄的作用,若left_table中記錄無法在right_table中找到對應(yīng)的記錄,則會被過濾掉;

WHERE字句,不管是涉及表left_table、表right_table上的限制條件,還是涉及2表連接的條件,都會對記錄集起到過濾作用,把不符合要求的記錄刷選掉;

jinja2獲取循環(huán)索引

jinja2獲取循環(huán){% for i in n %}的索引使用loop.index

 
 
 
  1. {% for i in names %}
  2. {{ loop.index }} //當(dāng)前是第x條
  3. {{ i.name }}
  4. {% endfor %} 

flask 重定向和錯誤

可以用redirect()函數(shù)把用戶重定向到其它地方。放棄請求并返回錯誤代碼,用abort()函數(shù)。

 
 
 
  1. from flask import abort, redirect, url_for
  2. @app.route('/')
  3. def index():
  4. return redirect(url_for('login'))
  5. @app.route('/login')
  6. def login():
  7. abort(401)
  8. this_is_never_executed() 

默認(rèn)情況下,錯誤代碼會顯示一個黑白的錯誤頁面。如果你要定制錯誤頁面,可以使用errorhandler()

裝飾器:

 
 
 
  1. from flask import render_template
  2. @app.errorhandler(404)
  3. def page_not_found(error):
  4. return render_template('page_not_found.html'), 404 

注意 render_template()調(diào)用之后的 404 。這告訴Flask,該頁的錯誤代碼是404 ,即沒有找到。默認(rèn)為200,也就是一切正常。

flask CSRF防護(hù)機(jī)制

 
 
 
  1. @app.before_request
  2. def csrf_protect():
  3. if request.method == "POST":
  4. token = session.pop('_csrf_token', None)
  5. if not token or token != request.form.get('_csrf_token'):
  6. abort(403)
  7. def some_random_string():
  8. return hashlib.sha256(os.urandom(16).hexdigest())
  9. def generate_csrf_token():
  10. if '_csrf_token' not in session:
  11. session['_csrf_token'] = some_random_string()
  12. return session['_csrf_token'] 

在flask的全局變量里面注冊 上面那個生成隨機(jī)token的函數(shù)

app.jinja_env.globals[‘csrf_token’] = generate_csrf_token

在網(wǎng)頁的模板是這么引入的

 
 
 
  1.  

flask上下文處理器

Flask 上下文處理器自動向模板的上下文中插入新變量。上下文處理器在模板渲染之前運行,并且可以在模板上下文中插入新值。上下文處理器是一個返回字典的函數(shù),這個字典的鍵值最終將傳入應(yīng)用中所有模板的上下文:

 
 
 
  1. @app.context_processor
  2. def inject_user():
  3. return dict(user=g.user) 

上面的上下文處理器使得模板可以使用一個名為user值為g.user的變量。不過這個例子不是很有意思,因為g在模板中本來就是可用的,但它解釋了上下文處理器是如何工作的。

變量不僅限于值,上下文處理器也可以使某個函數(shù)在模板中可用(由于Python允許傳遞函數(shù)):

 
 
 
  1. @app.context_processor
  2. def utility_processor():
  3. def format_price(amount, currency=u'€'):
  4. return u'{0:.2f}{1}.format(amount, currency)
  5. return dict(format_price=format_price) 

上面的上下文處理器使得format_price函數(shù)在所有模板中可用:

{{ format_price(0.33) }}

日志記錄

handler = logging.FileHandler(‘flask.log’, encoding=’UTF-8′)

1、請求之前設(shè)置requestId并記錄日志

每個URL請求之前,定義requestId并綁定到g

 
 
 
  1. @app.before_request
  2. def before_request():
  3. g.requestId = gen_requestId()
  4. logger.info("Start Once Access, and this requestId is %s" % g.requestId) 

2、請求之后添加響應(yīng)頭與記錄日志

每次返回數(shù)據(jù)中,帶上響應(yīng)頭,包含API版本和本次請求的requestId,以及允許所有域跨域訪問API, 記錄訪問日志

 
 
 
  1. @app.after_request
  2. def add_header(response):
  3. response.headers["X-SaintIC-Media-Type"] = "saintic.v1"
  4. response.headers["X-SaintIC-Request-Id"] = g.requestId
  5. response.headers["Access-Control-Allow-Origin"] = "*"
  6. logger.info(json.dumps({
  7. "AccessLog": {
  8. "status_code": response.status_code,
  9. "method": request.method,
  10. "ip": request.headers.get('X-Real-Ip', request.remote_addr),
  11. "url": request.url,
  12. "referer": request.headers.get('Referer'),
  13. "agent": request.headers.get("User-Agent"),
  14. "requestId": str(g.requestId),
  15. }
  16. }
  17. ))
  18. return response 

basicConfig方法可以滿足你在絕大多數(shù)場景下的使用需求,但是basicConfig有一個很大的缺點。調(diào)用basicConfig其實是給root logger添加了一個handler(FileHandler ),這樣當(dāng)你的程序和別的使用了 logging的第三方模塊一起工作時,會影響第三方模塊的logger行為。這是由logger的繼承特性決定的

 
 
 
  1. logging.basicConfig(level=logging.DEBUG,
  2. format='%(asctime)s %(levelname)s %(message)s',
  3. datefmt='%a, %d %b %Y %H:%M:%S',
  4. filename='logs/pro.log',
  5. filemode='w')
  6.  
  7. logging.debug('dddddddddd') 

MySQL字符編碼

除了設(shè)置數(shù)據(jù)庫的之外,由于dataset默認(rèn)創(chuàng)建數(shù)據(jù)庫和表的字符集不是utf8,所以需要自己設(shè)置,否則會中文亂碼,所以需要修改表的字符集

 
 
 
  1. my.cnf
  2. [client]
  3. default-character-set=utf8
  4. [mysqld]
  5. character-set-server=utf8
  6. collation-server=utf8_general_ci
  7. default-storage-engine=INNODB 

表的字符集

 
 
 
  1. show create table tasks;
  2. alter table tasks convert to character set utf8;  

文章名稱:Dataset基于SQLAlchemy的便利工具
文章鏈接:http://www.dlmjj.cn/article/dhgdche.html