python处理mysql中datetime和decimal的序列化

2022年8月14日 06:20 by wst

python小技巧

问题

在日常开发中, 你是否碰到过这样的问题:

1. mysql中的datetime字段, 用json.dumps的过程中报错, 说不支持这种类型.

2. mysql中的decimal字段, 在用json序列化的过程中,同样报不支持.

场景

场景一:

在电商系统中, 经常需要记录创建时间,比如订单创建时间、用户付款时间等等。当用户查看订单的时候,需要从数据库中取出“时间”返给前端。

在不同web框架中,处理方式也不一样,本人在使用sanic框架的respsonse.json方法时就报了错。

场景二:

在处理和钱相关的数据时,由于python的float会产生数据误差,一般采用decimal类型存储。包括在python中和mysql中。

解决方案

既然“sanic框架”和“json”包不支持上述情况,那么我们可以定制一下:对decimal类型、datetime类型进行特殊处理。下面分两种情况:json包和sanic框架。

json包中的定制:

#!/usr/bin/env python

"""
FileName: json_encoder
Author: wst
Email: movingheart000@gmail.com
Date: 2022/8/5 13:31:32
Desc: 能够处理deciaml类型的编码器
"""

import json
import datetime
from decimal import *


class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        # if passed in object is instance of Decimal
        # convert it to a string
        if isinstance(obj, Decimal):
            return str(obj)
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %X")
        # otherwise use the default behavior
        return json.JSONEncoder.default(self, obj)


if __name__ == "__main__":
    num = Decimal('3.14')
    json_str = json.dumps({'salary': num}, cls=DecimalEncoder)
    print(json_str)  # '{"salary": "3.14"}'
    print(type(json_str))  # <class 'str'>

    dt = json.dumps({"create_time": datetime.datetime.now()}, cls=DecimalEncoder)
    print("dt:", dt)  # dt: {"create_time": "2022-08-14 05:54:47"}
    print(type(dt))   # <class 'str'>

sanic框架中的定制(各种搜索都没找到解决方案,经过总结探索得出):

#!/usr/bin/env python

"""
FileName: pub
Author: wst
Email: movingheart000@gmail.com
Date: 2022/08/13 22:39:29
"""

from sanic import response
from functools import partial

from .json_encoder import DecimalEncoder

json_dumps = partial(dumps, cls=DecimalEncoder)


def resp_json(status: int = RespCode.OK, msg: str = None, data=None, headers: dict = None):
    """
    响应json
    :param status:返回的状态码
    :param msg: 状态解释
    :param data: 数据
    :param headers:响应头
    :return:
    """
    res = {"code": status, "msg": RespCode.desc.get(status)}
    if msg is not None:
        res["msg"] = msg
    if data is not None:
        res["data"] = data
    return response.json(res, headers=headers, dumps=json_dumps)  

注:关于partial的用法,参考这里:https://zhuanlan.zhihu.com/p/47124891

如果看完文章,还是不能解决问题,欢迎探讨。v:Beeb2b3


Comments(128) Add Your Comment

Pcmrrj
purchase lipitor generic <a href="https://lipiws.top/">atorvastatin generic</a> order lipitor for sale
Tdjscz
baycip pills - <a href="https://metroagyl.top/azithromycin/">buy clavulanate for sale</a> augmentin 625mg ca
Oeakii
buy ciprofloxacin sale - <a href="https://cipropro.top/">buy ciprofloxacin pill</a> buy augmentin generic
Nmholh
purchase metronidazole online - <a href="https://metroagyl.top/azithromycin/">zithromax 250mg drug</a> purchase azithromycin for sale
Zsugvv
where to buy ciprofloxacin without a prescription - <a href="https://septrim.top/doryx/">buy doryx no prescription</a> order erythromycin 250mg online
Lryhst
buy valtrex pills - <a href="https://gnantiviralp.com/">cheap valtrex 500mg</a> order zovirax 400mg for sale
Clopix
ivermectin 12mg tablets for humans - <a href="https://keflexin.top/">ciprofloxacin brand</a> buy tetracycline 250mg for sale
Daaeuc
buy metronidazole 200mg - <a href="https://metroagyl.top/clindamycin/">buy cleocin generic</a> buy azithromycin online cheap
Jsdito
ampicillin antibiotic <a href="https://ampiacil.top/penicillinused/">buy penicillin cheap</a> buy amoxil pill
Vgdywf
purchase lasix sale - <a href="https://antipathogenc.com/">order lasix generic</a> buy capoten 25 mg sale
Fngjcc
glucophage 500mg price - <a href="https://gnantiacidity.com/septra/">order septra generic</a> lincomycin over the counter
Sdgtpg
retrovir without prescription - <a href="https://canadiangnp.com/">order metformin 1000mg pill</a> order allopurinol 300mg online cheap
Yqaefx
generic clozapine 100mg - <a href="https://genonlinep.com/">order clozapine</a> cost famotidine
Nvkipp
generic seroquel - <a href="https://gnkantdepres.com/bupron/">buy bupron SR for sale</a> eskalith online buy
Irownt
anafranil for sale online - <a href="https://antdeponline.com/celexa/">celexa tablet</a> doxepin 75mg uk
Kqmokj
hydroxyzine us - <a href="https://antdepls.com/prozac/">order prozac 40mg for sale</a> buy endep paypal
Uxxhzw
augmentin 375mg for sale - <a href="https://atbioinfo.com/ethambutol/">generic ethambutol 1000mg</a> cheap cipro 500mg
Psargl
buy amoxil without prescription - <a href="https://atbioxotc.com/cefadroxil/">buy cheap cefadroxil</a> buy ciprofloxacin 1000mg for sale
Mmbbot
order cleocin 300mg generic - <a href="https://cadbiot.com/cefpodoxime/">vantin 200mg canada</a> buy chloramphenicol tablets
Vewgcu
zithromax 250mg price - <a href="https://gncatbp.com/">zithromax cost</a> purchase ciprofloxacin
Npdtup
stromectol over the counter - <a href="https://antibpl.com/tylquin/">purchase levaquin for sale</a> cefaclor 500mg without prescription
Kygzae
order ventolin pills - <a href="https://antxallergic.com/xsseroflo/">seroflo inhaler</a> order theo-24 Cr 400 mg online cheap
Llpuxj
brand clarinex 5mg - <a href="https://rxtallerg.com/flixotidespray/">flixotide for sale online</a> ventolin 2mg price
Umgzoo
where to buy depo-medrol without a prescription - <a href="https://ntallegpl.com/">medrol 8mg for sale</a> generic astelin 10 ml
Ykoloz
buy glyburide pills - <a href="https://prodeprpl.com/pioglitazone30/">purchase actos pills</a> dapagliflozin 10mg pill
Ouwcsq
buy repaglinide online cheap - <a href="https://depressinfo.com/jardiance25/">buy empagliflozin</a> buy jardiance 10mg online
Zocwll
glycomet where to buy - <a href="https://arxdepress.com/sitagliptin50/">order januvia 100mg online</a> buy precose pills
Oteucy
order generic terbinafine 250mg - <a href="https://treatfungusx.com/">lamisil pill</a> griseofulvin without prescription
Oxtdyp
buy rybelsus 14 mg generic - <a href="https://infodeppl.com/glucovance5/">buy generic glucovance online</a> order DDAVP sale
Duidgq
buy ketoconazole pills for sale - <a href="https://antifungusrp.com/itraconazole100/">itraconazole ca</a> sporanox 100mg sale
Gkijvv
order famvir without prescription - <a href="https://amvinherpes.com/">famciclovir without prescription</a> valaciclovir 500mg ca
Hnponm
oral digoxin - <a href="https://blpressureok.com/dipyridamole100/">purchase dipyridamole generic</a> furosemide 40mg price
Nsidjm
buy generic hydrochlorothiazide online - <a href="https://norvapril.com/felodipine/">purchase felodipine generic</a> zebeta 10mg generic
Etrjau
buy metoprolol generic - <a href="https://bloodpresspl.com/propranolol/">buy generic propranolol</a> nifedipine price
Qgzkwl
nitroglycerin cost - <a href="https://nitroproxl.com/indapamide/">indapamide 1.5mg uk</a> order diovan 160mg generic
Vyiyxb
zocor address - <a href="https://canescholest.com/fenofibrate/">fenofibrate fasten</a> lipitor shin
Xogpoz
crestor pills stride - <a href="https://antcholesterol.com/caduet5mg/">caduet buy similar</a> caduet pills design
Gotgov
buy viagra professional anyway - <a href="https://edsildps.com/superavana/">avana watson</a> levitra oral jelly online distinct
Fwobci
priligy self - <a href="https://promedprili.com/sildigra/">sildigra rise</a> cialis with dapoxetine stand
Qyetwl
cenforce alley - <a href="https://xcenforcem.com/cialistadalafil/">tadalafil cost</a> brand viagra boy
Zqbtvo
brand cialis require - <a href="https://probrandtad.com/penisole/">penisole grope</a> penisole abyss
Hkfefo
cialis soft tabs online ten - <a href="https://supervalip.com/viagrasuperactive/">viagra super active online father</a> viagra oral jelly fashion
Lbqlxd
brand cialis filch - <a href="https://probrandtad.com/apcalissx/">apcalis original</a> penisole over
Ldcszx
cialis soft tabs yawn - <a href="https://supervalip.com/cialisoraljelly/">cialis oral jelly pills bill</a> viagra oral jelly online mark
Xkphda
cenforce online chest - <a href="https://xcenforcem.com/zenegrasildenafil/">zenegra pills scramble</a> brand viagra myself
Heoxkk
dapoxetine angry - <a href="https://promedprili.com/cialiswithdapoxetine/">cialis with dapoxetine charge</a> cialis with dapoxetine fast
Gmmsus
acne treatment knock - <a href="https://placnemedx.com/">acne treatment sacred</a> acne treatment mine
Yjwczj
asthma medication check - <a href="https://bsasthmaps.com/">asthma medication south</a> asthma medication sky
Rfbjon
uti antibiotics singular - <a href="https://amenahealthp.com/">uti antibiotics morrow</a> uti antibiotics bald
Sgagkm
pills for treat prostatitis brief - <a href="https://xprosttreat.com/">prostatitis treatment walk</a> prostatitis pills later
Bvmdcz
valtrex online landscape - <a href="https://gnantiviralp.com/">valacyclovir shower</a> valtrex pills consult
Ywqigc
claritin brush - <a href="https://clatadine.top/">claritin mental</a> claritin soul
Expiju
claritin pills discuss - <a href="https://clatadine.top/">claritin plenty</a> claritin pills snatch
Wpncdz
dapoxetine shallow - <a href="https://prilixgn.top/">dapoxetine observe</a> dapoxetine nightmare
Tsixwl
promethazine letter - <a href="https://prohnrg.com/">promethazine bold</a> promethazine spin
Hjxjgi
ascorbic acid polish - <a href="https://ascxacid.com/">ascorbic acid alone</a> ascorbic acid current
Tvitks
biaxin sniff - <a href="https://gastropls.com/">biaxin pills telephone</a> cytotec pills wolf
Oggbah
florinef pills accurate - <a href="https://gastroplusp.com/propantoprazole/">pantoprazole log</a> lansoprazole pills pop
Wdkqoz
cost dulcolax - <a href="https://gastroinfop.com/liv52/">liv52 where to buy</a> buy liv52 without a prescription
Jidjmu
rabeprazole medication - <a href="https://gastrointesl.com/metoclopramide/">order metoclopramide generic</a> order motilium 10mg generic
Gpcjxl
order bactrim sale - <a href="https://ketiracet.com/">buy keppra 500mg for sale</a> buy tobramycin 5mg without prescription
Bbzsxp
eukroma online - <a href="https://dupsteron.com/">dydrogesterone online buy</a> duphaston price
Zbhxoy
purchase forxiga without prescription - <a href="https://precarbos.com/">buy generic precose 50mg</a> generic acarbose
Lukasl
griseofulvin online order - <a href="https://fulviseoful.com/">order fulvicin 250mg generic</a> order lopid 300mg
Scsrpc
purchase enalapril generic - <a href="https://doxapisin.com/">purchase doxazosin online</a> latanoprost eye drops
Oeqnsu
dimenhydrinate medication - <a href="https://prasilx.com/">prasugrel 10mg cheap</a> order actonel 35mg
Vcrdhx
how to buy etodolac - <a href="https://cilosetal.com/">pletal 100mg cheap</a> buy pletal 100mg pills
Jahpmd
buy feldene generic - <a href="https://rivastilons.com/">exelon medication</a> order exelon 6mg generic
Jviurs
nootropil 800mg brand - <a href="https://nootquin.com/levofloxacin/">levofloxacin 500mg generic</a> sinemet pills
Sopieb
buy hydrea paypal - <a href="https://hydroydrinfo.com/">brand hydroxyurea</a> robaxin 500mg tablet
Ilzmhv
buy divalproex generic - <a href="https://adepamox.com/topiramate/">how to get topamax without a prescription</a> buy topiramate online cheap
Jbopvl
norpace for sale - <a href="https://anorpica.com/lamotrigine/">lamotrigine 200mg drug</a> buy cheap thorazine
Xeicez
cytoxan pill - <a href="https://cycloxalp.com/trimetazidine/">order trimetazidine without prescription</a> purchase vastarel for sale
Ofhqkv
aldactone 25mg drug - <a href="https://aldantinep.com/naltrexone/">revia over the counter</a> naltrexone 50mg price
Ljdcpf
flexeril 15mg tablet - <a href="https://abflequine.com/olanzapine/">buy zyprexa 10mg online cheap</a> enalapril 10mg generic
Oirvva
buy ondansetron pills for sale - <a href="https://azofarininfo.com/oxybutynin/">oxytrol online buy</a> requip 2mg ca
Mfmwxu
buy ascorbic acid - <a href="https://mdacidinfo.com/bromhexine/">order bromhexine for sale</a> prochlorperazine order
Iplirj
durex gel buy online - <a href="https://xalaplinfo.com/durexcondoms/">buy durex condoms sale</a> buy latanoprost without prescription
Vaeujk
purchase rogaine sale - <a href="https://hairlossmedinfo.com/">rogaine sale</a> buy finasteride no prescription
Yiphee
arava price - <a href="https://infohealthybones.com/cartidin/">cheap cartidin tablets</a> order cartidin generic
Ebxcyy
tenormin online - <a href="https://heartmedinfox.com/">order atenolol pills</a> buy coreg 25mg
Rjqfac
calan online buy - <a href="https://infoheartdisea.com/">buy verapamil 240mg without prescription</a> purchase tenoretic pill
Fbisze
atorvastatin canada - <a href="https://infoxheartmed.com/lisinopril/">lisinopril tablet</a> bystolic buy online
Hrjzxg
cheap gasex sale - <a href="https://herbalinfomez.com/ashwagandha/">where can i buy ashwagandha</a> order diabecon generic
Rcrhbh
lasuna without prescription - <a href="https://infoherbalmz.com/">order lasuna pill</a> cost himcolin
Crbahy
noroxin pills - <a href="https://gmenshth.com/">buy cheap norfloxacin</a> confido pill
Bugsdb
cheap speman - <a href="https://spmensht.com/finasteride/">buy fincar paypal</a> purchase finasteride sale
Mjslqp
buy cheap finasteride - <a href="https://finmenura.com/alfuzosin/">buy alfuzosin 10 mg</a> uroxatral price
Mzjdzi
hytrin pills - <a href="https://hymenmax.com/dutasteride/">avodart 0.5mg brand</a> order priligy 90mg online cheap
Mxnfhu
generic oxcarbazepine - <a href="https://trileoxine.com/pirfenidone/">cheap pirfenex tablets</a> buy levothyroxine tablets
Lucesg
duphalac cost - <a href="https://duphalinfo.com/">buy generic duphalac online</a> betahistine without prescription
Iuwyku
cheap cyclosporine - <a href="https://asimusxate.com/gloperba/">generic colcrys 0.5mg</a> buy colcrys 0.5mg pills
Gvnguq
deflazacort over the counter - <a href="https://lazacort.com/">cheap deflazacort generic</a> brimonidine medication
Iqhzde
besivance price - <a href="https://besifxcist.com/">order generic besifloxacin</a> sildamax for sale
Xlankg
neurontin 600mg tablet - <a href="https://aneutrin.com/ibuprofen/">buy generic ibuprofen for sale</a> buy sulfasalazine pills
Xeqnqo
order probenecid 500 mg pills - <a href="https://bendoltol.com/carbamazepine/">carbamazepine 400mg cheap</a> brand tegretol
Svphir
order generic celebrex - <a href="https://celespas.com/flavoxate/">order urispas generic</a> cheap indomethacin
Tlzcha
cheap mebeverine 135 mg - <a href="https://coloxia.com/">buy mebeverine 135mg without prescription</a> buy pletal 100mg
Wmocjn
order voltaren 100mg pills - <a href="https://dicloltarin.com/">voltaren tablet</a> where can i buy aspirin
Zkcmej
rumalaya without prescription - <a href="https://rumaxtol.com/shallaki/">shallaki online buy</a> purchase amitriptyline pills
Pqalee
buy mestinon online cheap - <a href="https://mestonsx.com/asumatriptan/">sumatriptan brand</a> order azathioprine 25mg pills
Lnmhmr
order diclofenac generic - <a href="https://vovetosa.com/">purchase voveran sale</a> buy nimodipine online
Amquwh
baclofen 25mg ca - <a href="https://baclion.com/nspiroxicam/">buy piroxicam 20mg online cheap</a> buy piroxicam pills
Wsrvfn
mobic oral - <a href="https://meloxiptan.com/asrizatriptan/">maxalt 10mg over the counter</a> ketorolac cheap
Zgttrm
cyproheptadine 4mg uk - <a href="https://periheptadn.com/aszanaflex/">tizanidine over the counter</a> tizanidine medication
Krjeab
trihexyphenidyl pill - <a href="https://voltapll.com/diclofenacgel/">order diclofenac gel online cheap</a> buy cheap emulgel
Zpazmg
cefdinir 300mg tablet - <a href="https://omnixcin.com/clindamycin/">order cleocin</a> buy clindamycin online cheap
Wvrfqw
buy accutane - <a href="https://aisotane.com/asdeltasone/">buy deltasone 40mg online cheap</a> order deltasone 40mg generic
Zeiqaw
order prednisone - <a href="https://apreplson.com/">deltasone 20mg tablet</a> buy cheap generic elimite
Okiizf
buy permethrin generic - <a href="https://actizacs.com/tretinoin/">retin generic</a> tretinoin gel without prescription
Tebjgp
buy betamethasone no prescription - <a href="https://betnoson.com/awdifferin/">buy adapalene cream for sale</a> monobenzone price
Blemdg
order flagyl 400mg pill - <a href="https://ametronles.com/">buy flagyl 400mg online cheap</a> purchase cenforce online cheap
Cgdbwc
order amoxiclav sale - <a href="https://alevonted.com/">buy generic levothyroxine online</a> levothyroxine uk
Qmypfc
clindamycin where to buy - <a href="https://clinycinpl.com/">buy cleocin 300mg sale</a> buy indomethacin without a prescription
Fvpzqj
cozaar 25mg generic - <a href="https://cozartan.com/">oral hyzaar</a> order generic keflex 250mg
Qelmrc
eurax brand - <a href="https://aeuracream.com/abactroban/">how to get bactroban ointment without a prescription</a> buy generic aczone over the counter
Kzwmno
buy provigil 100mg pills - <a href="https://sleepagil.com/phenergan/">promethazine 25mg usa</a> melatonin without prescription
Cmhmli
bupropion tablet - <a href="https://bupropsl.com/">zyban oral</a> buy shuddha guggulu generic
Hmrciv
buy capecitabine 500 mg for sale - <a href="https://xelocap.com/danocrine/">danazol over the counter</a> danazol 100 mg over the counter
Jjmthv
order progesterone online cheap - <a href="https://apromid.com/">purchase prometrium pill</a> cheap clomiphene sale
Knyjqk
alendronate 35mg over the counter - <a href="https://pilaxmax.com/tamoxifen/">tamoxifen 20mg cost</a> buy generic medroxyprogesterone 5mg
Djgcfa
norethindrone brand - <a href="https://norethgep.com/yasmin/">cheap yasmin pills</a> buy yasmin generic
Privxu
estrace 1mg price - <a href="https://festrolp.com/">cost estrace 1mg</a> buy generic arimidex
Zmkllv
buy dostinex paypal - <a href="https://adostilin.com/">cabergoline drug</a> buy cheap alesse
Rhvxtg
гѓ—гѓ¬гѓ‰гѓ‹гѓі и–¬е±ЂгЃ§иІ·гЃ€г‚‹ - <a href="https://jpaonlinep.com/">гѓ—гѓ¬гѓ‰гѓ‹гѓійЂљиІ©гЃ§иІ·гЃ€гЃѕгЃ™гЃ‹</a> г‚ёг‚№гѓ­гѓћгѓѓг‚Ї гЃЉгЃ™гЃ™г‚Ѓ
Onauep
г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« её‚иІ© гЃЉгЃ™гЃ™г‚Ѓ - <a href="https://jpedpharm.com/">г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« еЂ¤ж®µ</a> г‚·г‚ўгѓЄг‚№гЃЇи–¬е±ЂгЃ§иІ·гЃ€г‚‹пјџ
Dkqiuk
プレドニン の購入 - <a href="https://jpanfarap.com/jpadoxycycline/">ドキシサイクリン通販</a> イソトレチノイン どこで買える
Gmksjt
eriacta wake - <a href="https://eriagra.com/dapcalisb/">apcalis loose</a> forzest stair