1.å¨flaskä¸ä½¿ç¨jsonifyåjson.dumpsçåºå«
å¨flaskä¸ä½¿ç¨jsonifyåjson.dumpsçåºå«
1.Content-Typeæåºå«
jsonifyçä½ç¨å®é ä¸å°±æ¯å°æä»¬ä¼ å ¥çjsonå½¢å¼æ°æ®åºååæ为jsonå符串ï¼ä½ä¸ºååºçbodyï¼å¹¶ä¸è®¾ç½®ååºçContent-Type为application/jsonï¼æé åºååºè¿åè³å®¢æ·ç«¯ãjsonifyçé¨åæºç å¦ä¸ï¼
def jsonify(*args,源码solr源码4.5结构 **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
å¯ä»¥çåºjsonifyå®é ä¸ä¹æ¯ä½¿ç¨äºjson.dumpsæ¥åºååjsonå½¢å¼çæ°æ®ï¼ä½ä¸ºååºæ£æè¿åãindent表示jsonæ ¼å¼åç缩è¿ï¼è¥æ¯Ajax请æ±åä¸ç¼©è¿ï¼å 为ä¸è¬Ajaxæ°æ®æ²¡å¿ è¦ç´æ¥å±ç¤ºï¼ï¼å¦å缩è¿2æ ¼ãä½æ³å¿ ä»ç¬¬ä¸é¨åçå®éªç»ææ们已ç»çåºæ¥äºï¼ä½¿ç¨jsonifyæ¶ååºçContent-Typeå段å¼ä¸ºapplication/jsonï¼è使ç¨json.dumpsæ¶è¯¥å段å¼ä¸ºtext/htmlãContent-Typeå³å®äºæ¥æ¶æ°æ®çä¸æ¹å¦ä½çå¾ æ°æ®ï¼å¦ä½å¤çæ°æ®ï¼å¦ææ¯application/jsonï¼åå¯ä»¥ç´æ¥å½åjson对象å¤çï¼è¥æ¯text/htmlï¼åè¿è¦å°ææ¬å¯¹è±¡è½¬å为json对象ååå¤çï¼ä¸ªäººç解ï¼æ误请ææ£ï¼ã
2.æ¥ååæ°æåºå«
jsonifyå¯ä»¥æ¥ååpythonä¸çdictæé å¨åæ ·çåæ°ï¼å¦ä¸å¾ã
èjson.dumpsæ¯jsonifyå¯ä»¥å¤æ¥ålistç±»ååä¸äºå ¶ä»ç±»åçåæ°ãä½æè¯äºä¸ä¸ï¼å½¢å¼ä¸ºkey1=value1ï¼[key2=value2,...]è¿æ ·çåæ°æ¯ä¸è¡çï¼ä¼æ¥åºâTypeError: dumps() takes exactly 1 argument (0 given)âè¿ä¸é误ï¼èjsonifyä¸ä¼æ¥é并è½æ£å¸¸è¿åæ°æ®ã
æåï¼æ们å¯ä»¥ä½¿ç¨flaskä¸çmake_responseæ¹æ³æè ç´æ¥éè¿Responseç±»ï¼éè¿è®¾ç½®mimetypeåæ°æ¥è¾¾å°å使ç¨jsonifyå·®ä¸å¤çææï¼ä½å°åç¹ä»£ç ä½ä¹èä¸ä¸ºå¢ï¼åµä¸ç®æ´ä¸ç¹æ´ä¸å®¹æåºéï¼åæ°è¶å¤è°è¯åç»´æ¤å°±è¶éº»ç¦ãå½ç¶ï¼ä½¿ç¨åªä¸ªå¹¶ä¸æ¯ç»å¯¹çï¼å¿ è¦æ¶è¦æ ¹æ®å端çæ°æ®å¤çæ¹å¼æ¥å³å®ã