diff --git "a/swe-bench-lite/pallets#flask#d8c37f43724cd9fb0870f77877b7c4c7e38a19e0.graph.json" "b/swe-bench-lite/pallets#flask#d8c37f43724cd9fb0870f77877b7c4c7e38a19e0.graph.json" new file mode 100644--- /dev/null +++ "b/swe-bench-lite/pallets#flask#d8c37f43724cd9fb0870f77877b7c4c7e38a19e0.graph.json" @@ -0,0 +1 @@ +{"edges":[{"edgeType":"contains","source":791,"target":254},{"edgeType":"contains","source":770,"target":773},{"edgeType":"contains","source":151,"target":208},{"edgeType":"contains","source":146,"target":363},{"edgeType":"imports","source":348,"target":719},{"edgeType":"contains","source":580,"target":585},{"edgeType":"contains","source":146,"target":495},{"edgeType":"contains","source":417,"target":419},{"edgeType":"contains","source":713,"target":690},{"edgeType":"contains","source":2,"target":5},{"edgeType":"contains","source":880,"target":996},{"edgeType":"contains","source":128,"target":129},{"edgeType":"contains","source":2,"target":137},{"edgeType":"calls","source":343,"target":366},{"edgeType":"contains","source":701,"target":269},{"edgeType":"contains","source":809,"target":290},{"edgeType":"contains","source":865,"target":866},{"edgeType":"contains","source":928,"target":961},{"edgeType":"contains","source":589,"target":635},{"edgeType":"contains","source":297,"target":306},{"edgeType":"contains","source":514,"target":516},{"edgeType":"calls","source":267,"target":276},{"edgeType":"contains","source":146,"target":362},{"edgeType":"contains","source":98,"target":859},{"edgeType":"contains","source":146,"target":428},{"edgeType":"contains","source":146,"target":494},{"edgeType":"contains","source":145,"target":525},{"edgeType":"contains","source":580,"target":584},{"edgeType":"contains","source":937,"target":946},{"edgeType":"contains","source":2,"target":4},{"edgeType":"contains","source":113,"target":593},{"edgeType":"calls","source":680,"target":290},{"edgeType":"contains","source":949,"target":970},{"edgeType":"contains","source":137,"target":906},{"edgeType":"calls","source":957,"target":952},{"edgeType":"calls","source":844,"target":425},{"edgeType":"contains","source":880,"target":995},{"edgeType":"imports","source":348,"target":122},{"edgeType":"imports","source":873,"target":958},{"edgeType":"contains","source":770,"target":775},{"edgeType":"contains","source":958,"target":959},{"edgeType":"contains","source":668,"target":171},{"edgeType":"contains","source":324,"target":331},{"edgeType":"imports","source":668,"target":112},{"edgeType":"contains","source":318,"target":319},{"edgeType":"contains","source":2,"target":865},{"edgeType":"contains","source":146,"target":497},{"edgeType":"contains","source":146,"target":498},{"edgeType":"contains","source":64,"target":67},{"edgeType":"contains","source":880,"target":998},{"edgeType":"contains","source":4,"target":11},{"edgeType":"contains","source":2,"target":7},{"edgeType":"contains","source":589,"target":638},{"edgeType":"contains","source":136,"target":147},{"edgeType":"contains","source":6,"target":15},{"edgeType":"imports","source":113,"target":140},{"edgeType":"contains","source":2,"target":337},{"edgeType":"contains","source":660,"target":352},{"edgeType":"contains","source":297,"target":308},{"edgeType":"contains","source":151,"target":209},{"edgeType":"contains","source":543,"target":544},{"edgeType":"contains","source":580,"target":454},{"edgeType":"contains","source":415,"target":416},{"edgeType":"contains","source":713,"target":691},{"edgeType":"contains","source":146,"target":496},{"edgeType":"contains","source":880,"target":997},{"edgeType":"contains","source":97,"target":100},{"edgeType":"contains","source":668,"target":566},{"edgeType":"contains","source":2,"target":6},{"edgeType":"contains","source":7,"target":908},{"edgeType":"contains","source":589,"target":637},{"edgeType":"calls","source":156,"target":152},{"edgeType":"contains","source":745,"target":293},{"edgeType":"imports","source":145,"target":140},{"edgeType":"contains","source":823,"target":848},{"edgeType":"contains","source":454,"target":465},{"edgeType":"contains","source":928,"target":966},{"edgeType":"contains","source":2,"target":339},{"edgeType":"contains","source":828,"target":829},{"edgeType":"contains","source":146,"target":235},{"edgeType":"contains","source":679,"target":361},{"edgeType":"calls","source":595,"target":675},{"edgeType":"contains","source":4,"target":739},{"edgeType":"calls","source":425,"target":264},{"edgeType":"contains","source":33,"target":39},{"edgeType":"calls","source":164,"target":163},{"edgeType":"contains","source":97,"target":103},{"edgeType":"contains","source":589,"target":640},{"edgeType":"contains","source":701,"target":207},{"edgeType":"imports","source":873,"target":691},{"edgeType":"contains","source":949,"target":975},{"edgeType":"contains","source":928,"target":965},{"edgeType":"contains","source":879,"target":502},{"edgeType":"imports","source":348,"target":121},{"edgeType":"calls","source":283,"target":304},{"edgeType":"contains","source":894,"target":896},{"edgeType":"contains","source":352,"target":389},{"edgeType":"calls","source":398,"target":373},{"edgeType":"contains","source":543,"target":546},{"edgeType":"contains","source":713,"target":693},{"edgeType":"imports","source":99,"target":110},{"edgeType":"imports","source":668,"target":111},{"edgeType":"contains","source":673,"target":678},{"edgeType":"contains","source":514,"target":454},{"edgeType":"contains","source":318,"target":320},{"edgeType":"contains","source":104,"target":744},{"edgeType":"contains","source":146,"target":499},{"edgeType":"calls","source":170,"target":174},{"edgeType":"calls","source":391,"target":392},{"edgeType":"calls","source":610,"target":606},{"edgeType":"contains","source":2,"target":867},{"edgeType":"contains","source":2,"target":8},{"edgeType":"contains","source":7,"target":910},{"edgeType":"imports","source":668,"target":507},{"edgeType":"contains","source":668,"target":172},{"edgeType":"contains","source":760,"target":887},{"edgeType":"calls","source":253,"target":244},{"edgeType":"calls","source":388,"target":287},{"edgeType":"contains","source":949,"target":974},{"edgeType":"contains","source":823,"target":850},{"edgeType":"contains","source":673,"target":681},{"edgeType":"contains","source":551,"target":433},{"edgeType":"contains","source":453,"target":564},{"edgeType":"contains","source":45,"target":65},{"edgeType":"contains","source":352,"target":392},{"edgeType":"contains","source":668,"target":572},{"edgeType":"contains","source":98,"target":668},{"edgeType":"contains","source":541,"target":545},{"edgeType":"contains","source":151,"target":214},{"edgeType":"contains","source":27,"target":29},{"edgeType":"contains","source":58,"target":59},{"edgeType":"contains","source":151,"target":215},{"edgeType":"contains","source":152,"target":184},{"edgeType":"imports","source":809,"target":559},{"edgeType":"contains","source":311,"target":341},{"edgeType":"contains","source":949,"target":977},{"edgeType":"contains","source":823,"target":853},{"edgeType":"contains","source":37,"target":49},{"edgeType":"calls","source":837,"target":839},{"edgeType":"contains","source":753,"target":777},{"edgeType":"calls","source":607,"target":172},{"edgeType":"contains","source":894,"target":898},{"edgeType":"contains","source":514,"target":522},{"edgeType":"contains","source":987,"target":988},{"edgeType":"imports","source":932,"target":117},{"edgeType":"contains","source":27,"target":820},{"edgeType":"contains","source":809,"target":824},{"edgeType":"contains","source":146,"target":236},{"edgeType":"contains","source":352,"target":391},{"edgeType":"contains","source":151,"target":213},{"edgeType":"contains","source":98,"target":932},{"edgeType":"contains","source":27,"target":28},{"edgeType":"contains","source":593,"target":781},{"edgeType":"imports","source":660,"target":290},{"edgeType":"calls","source":197,"target":198},{"edgeType":"calls","source":680,"target":288},{"edgeType":"imports","source":859,"target":860},{"edgeType":"contains","source":2,"target":76},{"edgeType":"contains","source":207,"target":261},{"edgeType":"contains","source":90,"target":453},{"edgeType":"contains","source":873,"target":359},{"edgeType":"contains","source":589,"target":641},{"edgeType":"imports","source":873,"target":690},{"edgeType":"contains","source":949,"target":976},{"edgeType":"calls","source":377,"target":360},{"edgeType":"imports","source":791,"target":141},{"edgeType":"calls","source":754,"target":763},{"edgeType":"calls","source":850,"target":826},{"edgeType":"contains","source":859,"target":863},{"edgeType":"contains","source":673,"target":683},{"edgeType":"calls","source":595,"target":605},{"edgeType":"contains","source":7,"target":56},{"edgeType":"contains","source":454,"target":469},{"edgeType":"contains","source":4,"target":347},{"edgeType":"contains","source":879,"target":111},{"edgeType":"contains","source":729,"target":731},{"edgeType":"calls","source":356,"target":152},{"edgeType":"imports","source":113,"target":150},{"edgeType":"contains","source":823,"target":856},{"edgeType":"contains","source":879,"target":507},{"edgeType":"calls","source":240,"target":247},{"edgeType":"imports","source":348,"target":397},{"edgeType":"contains","source":151,"target":217},{"edgeType":"contains","source":146,"target":372},{"edgeType":"imports","source":348,"target":132},{"edgeType":"contains","source":146,"target":504},{"edgeType":"contains","source":145,"target":535},{"edgeType":"contains","source":958,"target":304},{"edgeType":"contains","source":949,"target":979},{"edgeType":"contains","source":97,"target":107},{"edgeType":"contains","source":753,"target":779},{"edgeType":"contains","source":589,"target":644},{"edgeType":"contains","source":2,"target":79},{"edgeType":"contains","source":514,"target":524},{"edgeType":"calls","source":754,"target":762},{"edgeType":"contains","source":958,"target":964},{"edgeType":"contains","source":352,"target":393},{"edgeType":"contains","source":698,"target":700},{"edgeType":"imports","source":873,"target":507},{"edgeType":"contains","source":823,"target":855},{"edgeType":"calls","source":890,"target":774},{"edgeType":"contains","source":793,"target":794},{"edgeType":"contains","source":25,"target":818},{"edgeType":"calls","source":433,"target":407},{"edgeType":"contains","source":603,"target":606},{"edgeType":"contains","source":473,"target":474},{"edgeType":"contains","source":311,"target":343},{"edgeType":"contains","source":27,"target":30},{"edgeType":"calls","source":961,"target":952},{"edgeType":"calls","source":360,"target":358},{"edgeType":"contains","source":146,"target":371},{"edgeType":"contains","source":311,"target":342},{"edgeType":"contains","source":25,"target":26},{"edgeType":"contains","source":146,"target":503},{"edgeType":"contains","source":97,"target":106},{"edgeType":"contains","source":949,"target":978},{"edgeType":"contains","source":668,"target":110},{"edgeType":"contains","source":4,"target":16},{"edgeType":"calls","source":556,"target":426},{"edgeType":"contains","source":753,"target":778},{"edgeType":"imports","source":809,"target":112},{"edgeType":"contains","source":543,"target":553},{"edgeType":"contains","source":352,"target":396},{"edgeType":"contains","source":760,"target":895},{"edgeType":"contains","source":698,"target":703},{"edgeType":"contains","source":352,"target":462},{"edgeType":"contains","source":91,"target":559},{"edgeType":"contains","source":99,"target":311},{"edgeType":"contains","source":673,"target":685},{"edgeType":"contains","source":339,"target":667},{"edgeType":"contains","source":822,"target":823},{"edgeType":"calls","source":892,"target":847},{"edgeType":"contains","source":146,"target":241},{"edgeType":"contains","source":589,"target":646},{"edgeType":"contains","source":146,"target":242},{"edgeType":"contains","source":151,"target":153},{"edgeType":"contains","source":120,"target":123},{"edgeType":"contains","source":151,"target":219},{"edgeType":"calls","source":393,"target":395},{"edgeType":"contains","source":7,"target":587},{"edgeType":"contains","source":146,"target":506},{"edgeType":"contains","source":454,"target":471},{"edgeType":"calls","source":449,"target":377},{"edgeType":"contains","source":527,"target":454},{"edgeType":"contains","source":7,"target":57},{"edgeType":"contains","source":352,"target":461},{"edgeType":"calls","source":375,"target":357},{"edgeType":"imports","source":791,"target":140},{"edgeType":"contains","source":6,"target":22},{"edgeType":"contains","source":673,"target":684},{"edgeType":"contains","source":698,"target":702},{"edgeType":"calls","source":442,"target":460},{"edgeType":"imports","source":145,"target":148},{"edgeType":"contains","source":879,"target":112},{"edgeType":"contains","source":2,"target":344},{"edgeType":"contains","source":47,"target":931},{"edgeType":"contains","source":352,"target":395},{"edgeType":"calls","source":147,"target":158},{"edgeType":"contains","source":102,"target":481},{"edgeType":"contains","source":603,"target":608},{"edgeType":"contains","source":668,"target":244},{"edgeType":"imports","source":745,"target":112},{"edgeType":"contains","source":151,"target":152},{"edgeType":"contains","source":589,"target":645},{"edgeType":"contains","source":151,"target":218},{"edgeType":"imports","source":348,"target":131},{"edgeType":"contains","source":27,"target":32},{"edgeType":"contains","source":146,"target":505},{"edgeType":"contains","source":145,"target":536},{"edgeType":"calls","source":415,"target":373},{"edgeType":"imports","source":745,"target":244},{"edgeType":"contains","source":76,"target":891},{"edgeType":"contains","source":698,"target":705},{"edgeType":"contains","source":981,"target":983},{"edgeType":"contains","source":791,"target":795},{"edgeType":"contains","source":4,"target":21},{"edgeType":"contains","source":352,"target":398},{"edgeType":"contains","source":91,"target":561},{"edgeType":"contains","source":7,"target":60},{"edgeType":"contains","source":99,"target":445},{"edgeType":"contains","source":566,"target":569},{"edgeType":"contains","source":564,"target":565},{"edgeType":"contains","source":277,"target":279},{"edgeType":"calls","source":408,"target":386},{"edgeType":"calls","source":994,"target":982},{"edgeType":"calls","source":459,"target":457},{"edgeType":"contains","source":102,"target":551},{"edgeType":"contains","source":589,"target":648},{"edgeType":"imports","source":873,"target":237},{"edgeType":"contains","source":7,"target":589},{"edgeType":"contains","source":151,"target":155},{"edgeType":"contains","source":146,"target":310},{"edgeType":"contains","source":151,"target":221},{"edgeType":"contains","source":98,"target":873},{"edgeType":"contains","source":146,"target":442},{"edgeType":"contains","source":146,"target":508},{"edgeType":"calls","source":360,"target":355},{"edgeType":"contains","source":2,"target":17},{"edgeType":"calls","source":426,"target":357},{"edgeType":"contains","source":679,"target":765},{"edgeType":"contains","source":339,"target":933},{"edgeType":"contains","source":6,"target":24},{"edgeType":"contains","source":543,"target":554},{"edgeType":"contains","source":698,"target":704},{"edgeType":"contains","source":4,"target":20},{"edgeType":"contains","source":981,"target":982},{"edgeType":"contains","source":729,"target":734},{"edgeType":"contains","source":99,"target":444},{"edgeType":"calls","source":246,"target":254},{"edgeType":"contains","source":473,"target":478},{"edgeType":"contains","source":603,"target":610},{"edgeType":"contains","source":146,"target":243},{"edgeType":"contains","source":589,"target":647},{"edgeType":"contains","source":151,"target":154},{"edgeType":"contains","source":120,"target":124},{"edgeType":"calls","source":402,"target":373},{"edgeType":"contains","source":146,"target":375},{"edgeType":"contains","source":102,"target":748},{"edgeType":"contains","source":7,"target":588},{"edgeType":"calls","source":229,"target":253},{"edgeType":"imports","source":873,"target":502},{"edgeType":"calls","source":394,"target":357},{"edgeType":"contains","source":679,"target":764},{"edgeType":"contains","source":98,"target":145},{"edgeType":"contains","source":791,"target":797},{"edgeType":"contains","source":879,"target":117},{"edgeType":"calls","source":417,"target":373},{"edgeType":"contains","source":981,"target":985},{"edgeType":"contains","source":531,"target":533},{"edgeType":"contains","source":564,"target":567},{"edgeType":"contains","source":277,"target":281},{"edgeType":"contains","source":99,"target":447},{"edgeType":"contains","source":760,"target":899},{"edgeType":"contains","source":698,"target":707},{"edgeType":"contains","source":589,"target":650},{"edgeType":"imports","source":809,"target":171},{"edgeType":"imports","source":453,"target":174},{"edgeType":"contains","source":151,"target":157},{"edgeType":"contains","source":98,"target":809},{"edgeType":"contains","source":151,"target":223},{"edgeType":"calls","source":812,"target":813},{"edgeType":"contains","source":146,"target":510},{"edgeType":"calls","source":360,"target":357},{"edgeType":"contains","source":339,"target":869},{"edgeType":"contains","source":352,"target":399},{"edgeType":"imports","source":668,"target":117},{"edgeType":"calls","source":858,"target":839},{"edgeType":"contains","source":136,"target":158},{"edgeType":"contains","source":99,"target":446},{"edgeType":"contains","source":531,"target":532},{"edgeType":"contains","source":339,"target":340},{"edgeType":"contains","source":668,"target":513},{"edgeType":"contains","source":102,"target":485},{"edgeType":"calls","source":174,"target":176},{"edgeType":"contains","source":146,"target":245},{"edgeType":"contains","source":145,"target":276},{"edgeType":"calls","source":170,"target":168},{"edgeType":"contains","source":589,"target":649},{"edgeType":"contains","source":151,"target":222},{"edgeType":"contains","source":146,"target":377},{"edgeType":"imports","source":873,"target":566},{"edgeType":"contains","source":113,"target":541},{"edgeType":"contains","source":679,"target":766},{"edgeType":"contains","source":25,"target":332},{"edgeType":"contains","source":880,"target":980},{"edgeType":"contains","source":745,"target":1003},{"edgeType":"contains","source":873,"target":140},{"edgeType":"contains","source":748,"target":844},{"edgeType":"contains","source":8,"target":66},{"edgeType":"imports","source":660,"target":676},{"edgeType":"contains","source":91,"target":598},{"edgeType":"contains","source":825,"target":835},{"edgeType":"calls","source":152,"target":159},{"edgeType":"contains","source":698,"target":676},{"edgeType":"contains","source":627,"target":631},{"edgeType":"contains","source":2,"target":318},{"edgeType":"contains","source":2,"target":451},{"edgeType":"contains","source":928,"target":945},{"edgeType":"contains","source":589,"target":619},{"edgeType":"calls","source":994,"target":351},{"edgeType":"imports","source":873,"target":150},{"edgeType":"contains","source":7,"target":626},{"edgeType":"contains","source":151,"target":192},{"edgeType":"contains","source":146,"target":413},{"edgeType":"contains","source":2,"target":715},{"edgeType":"contains","source":146,"target":479},{"edgeType":"calls","source":363,"target":357},{"edgeType":"contains","source":352,"target":435},{"edgeType":"contains","source":573,"target":454},{"edgeType":"contains","source":668,"target":614},{"edgeType":"contains","source":311,"target":384},{"edgeType":"calls","source":862,"target":874},{"edgeType":"contains","source":753,"target":754},{"edgeType":"contains","source":745,"target":1002},{"edgeType":"calls","source":380,"target":357},{"edgeType":"contains","source":91,"target":597},{"edgeType":"imports","source":660,"target":677},{"edgeType":"imports","source":873,"target":614},{"edgeType":"calls","source":774,"target":761},{"edgeType":"contains","source":25,"target":727},{"edgeType":"contains","source":825,"target":834},{"edgeType":"contains","source":49,"target":50},{"edgeType":"contains","source":237,"target":299},{"edgeType":"contains","source":49,"target":116},{"edgeType":"contains","source":589,"target":618},{"edgeType":"calls","source":245,"target":248},{"edgeType":"calls","source":940,"target":174},{"edgeType":"calls","source":267,"target":293},{"edgeType":"contains","source":352,"target":434},{"edgeType":"imports","source":102,"target":134},{"edgeType":"contains","source":748,"target":912},{"edgeType":"contains","source":745,"target":1005},{"edgeType":"contains","source":98,"target":119},{"edgeType":"contains","source":873,"target":1001},{"edgeType":"imports","source":348,"target":502},{"edgeType":"calls","source":613,"target":536},{"edgeType":"imports","source":873,"target":677},{"edgeType":"contains","source":99,"target":286},{"edgeType":"contains","source":453,"target":543},{"edgeType":"contains","source":146,"target":151},{"edgeType":"imports","source":809,"target":811},{"edgeType":"contains","source":893,"target":909},{"edgeType":"contains","source":146,"target":283},{"edgeType":"calls","source":877,"target":875},{"edgeType":"contains","source":873,"target":1000},{"edgeType":"contains","source":146,"target":349},{"edgeType":"calls","source":975,"target":280},{"edgeType":"contains","source":34,"target":54},{"edgeType":"calls","source":546,"target":168},{"edgeType":"contains","source":589,"target":621},{"edgeType":"contains","source":793,"target":837},{"edgeType":"calls","source":312,"target":287},{"edgeType":"contains","source":91,"target":599},{"edgeType":"contains","source":698,"target":677},{"edgeType":"contains","source":593,"target":695},{"edgeType":"contains","source":451,"target":935},{"edgeType":"contains","source":47,"target":48},{"edgeType":"contains","source":451,"target":802},{"edgeType":"contains","source":589,"target":620},{"edgeType":"calls","source":243,"target":246},{"edgeType":"contains","source":98,"target":713},{"edgeType":"imports","source":660,"target":674},{"edgeType":"imports","source":91,"target":146},{"edgeType":"contains","source":151,"target":193},{"edgeType":"contains","source":873,"target":999},{"edgeType":"contains","source":146,"target":480},{"edgeType":"calls","source":980,"target":984},{"edgeType":"contains","source":120,"target":232},{"edgeType":"contains","source":879,"target":883},{"edgeType":"contains","source":745,"target":1007},{"edgeType":"imports","source":348,"target":500},{"edgeType":"contains","source":745,"target":875},{"edgeType":"contains","source":473,"target":454},{"edgeType":"imports","source":348,"target":566},{"edgeType":"contains","source":104,"target":926},{"edgeType":"contains","source":5,"target":31},{"edgeType":"imports","source":113,"target":121},{"edgeType":"contains","source":2,"target":58},{"edgeType":"imports","source":809,"target":677},{"edgeType":"contains","source":237,"target":239},{"edgeType":"calls","source":156,"target":229},{"edgeType":"contains","source":76,"target":77},{"edgeType":"contains","source":2,"target":323},{"edgeType":"calls","source":377,"target":381},{"edgeType":"contains","source":352,"target":373},{"edgeType":"calls","source":516,"target":168},{"edgeType":"calls","source":363,"target":353},{"edgeType":"contains","source":541,"target":592},{"edgeType":"contains","source":151,"target":196},{"edgeType":"imports","source":102,"target":132},{"edgeType":"contains","source":146,"target":482},{"edgeType":"contains","source":748,"target":913},{"edgeType":"contains","source":745,"target":1006},{"edgeType":"contains","source":748,"target":847},{"edgeType":"imports","source":873,"target":280},{"edgeType":"imports","source":348,"target":501},{"edgeType":"imports","source":873,"target":676},{"edgeType":"contains","source":589,"target":623},{"edgeType":"calls","source":837,"target":852},{"edgeType":"calls","source":259,"target":272},{"edgeType":"imports","source":348,"target":171},{"edgeType":"imports","source":348,"target":237},{"edgeType":"contains","source":45,"target":46},{"edgeType":"calls","source":377,"target":380},{"edgeType":"imports","source":660,"target":672},{"edgeType":"contains","source":352,"target":438},{"edgeType":"calls","source":545,"target":259},{"edgeType":"contains","source":146,"target":350},{"edgeType":"calls","source":774,"target":427},{"edgeType":"imports","source":873,"target":541},{"edgeType":"contains","source":120,"target":234},{"edgeType":"contains","source":879,"target":885},{"edgeType":"contains","source":745,"target":877},{"edgeType":"contains","source":745,"target":811},{"edgeType":"contains","source":102,"target":924},{"edgeType":"contains","source":4,"target":857},{"edgeType":"contains","source":555,"target":557},{"edgeType":"contains","source":237,"target":307},{"edgeType":"contains","source":668,"target":159},{"edgeType":"imports","source":873,"target":673},{"edgeType":"contains","source":5,"target":33},{"edgeType":"contains","source":138,"target":139},{"edgeType":"imports","source":91,"target":141},{"edgeType":"imports","source":660,"target":669},{"edgeType":"calls","source":974,"target":969},{"edgeType":"contains","source":25,"target":735},{"edgeType":"contains","source":27,"target":871},{"edgeType":"contains","source":151,"target":198},{"edgeType":"contains","source":146,"target":353},{"edgeType":"contains","source":146,"target":418},{"edgeType":"contains","source":879,"target":884},{"edgeType":"contains","source":748,"target":915},{"edgeType":"contains","source":745,"target":1008},{"edgeType":"contains","source":627,"target":636},{"edgeType":"contains","source":120,"target":233},{"edgeType":"contains","source":146,"target":484},{"edgeType":"contains","source":1003,"target":1004},{"edgeType":"contains","source":102,"target":923},{"edgeType":"contains","source":811,"target":812},{"edgeType":"contains","source":551,"target":746},{"edgeType":"imports","source":809,"target":676},{"edgeType":"contains","source":8,"target":930},{"edgeType":"contains","source":823,"target":836},{"edgeType":"contains","source":589,"target":625},{"edgeType":"contains","source":237,"target":240},{"edgeType":"contains","source":136,"target":199},{"edgeType":"imports","source":873,"target":674},{"edgeType":"imports","source":660,"target":670},{"edgeType":"calls","source":216,"target":220},{"edgeType":"contains","source":385,"target":408},{"edgeType":"calls","source":577,"target":194},{"edgeType":"contains","source":151,"target":197},{"edgeType":"contains","source":932,"target":958},{"edgeType":"contains","source":151,"target":200},{"edgeType":"contains","source":146,"target":355},{"edgeType":"contains","source":745,"target":813},{"edgeType":"contains","source":840,"target":841},{"edgeType":"calls","source":267,"target":351},{"edgeType":"contains","source":146,"target":487},{"edgeType":"contains","source":520,"target":521},{"edgeType":"contains","source":809,"target":150},{"edgeType":"contains","source":5,"target":35},{"edgeType":"contains","source":2,"target":128},{"edgeType":"calls","source":387,"target":397},{"edgeType":"contains","source":748,"target":918},{"edgeType":"contains","source":753,"target":763},{"edgeType":"contains","source":113,"target":783},{"edgeType":"imports","source":102,"target":277},{"edgeType":"imports","source":873,"target":687},{"edgeType":"contains","source":760,"target":876},{"edgeType":"contains","source":136,"target":203},{"edgeType":"calls","source":725,"target":556},{"edgeType":"contains","source":25,"target":737},{"edgeType":"calls","source":343,"target":110},{"edgeType":"contains","source":49,"target":125},{"edgeType":"contains","source":928,"target":953},{"edgeType":"contains","source":668,"target":689},{"edgeType":"contains","source":879,"target":886},{"edgeType":"contains","source":146,"target":486},{"edgeType":"contains","source":811,"target":814},{"edgeType":"imports","source":348,"target":117},{"edgeType":"contains","source":555,"target":558},{"edgeType":"contains","source":2,"target":61},{"edgeType":"contains","source":823,"target":838},{"edgeType":"contains","source":113,"target":782},{"edgeType":"calls","source":392,"target":373},{"edgeType":"contains","source":748,"target":917},{"edgeType":"contains","source":753,"target":762},{"edgeType":"contains","source":5,"target":34},{"edgeType":"contains","source":297,"target":298},{"edgeType":"contains","source":136,"target":202},{"edgeType":"contains","source":13,"target":51},{"edgeType":"contains","source":352,"target":376},{"edgeType":"imports","source":113,"target":135},{"edgeType":"contains","source":146,"target":156},{"edgeType":"imports","source":348,"target":513},{"edgeType":"contains","source":928,"target":952},{"edgeType":"imports","source":873,"target":688},{"edgeType":"contains","source":146,"target":288},{"edgeType":"calls","source":375,"target":372},{"edgeType":"imports","source":809,"target":159},{"edgeType":"contains","source":146,"target":357},{"edgeType":"contains","source":745,"target":749},{"edgeType":"contains","source":207,"target":250},{"edgeType":"contains","source":25,"target":144},{"edgeType":"contains","source":318,"target":905},{"edgeType":"contains","source":710,"target":711},{"edgeType":"contains","source":146,"target":489},{"edgeType":"calls","source":353,"target":264},{"edgeType":"calls","source":316,"target":420},{"edgeType":"calls","source":381,"target":387},{"edgeType":"contains","source":454,"target":455},{"edgeType":"contains","source":297,"target":301},{"edgeType":"calls","source":316,"target":354},{"edgeType":"calls","source":189,"target":195},{"edgeType":"contains","source":113,"target":719},{"edgeType":"contains","source":879,"target":889},{"edgeType":"calls","source":408,"target":343},{"edgeType":"contains","source":760,"target":878},{"edgeType":"contains","source":822,"target":938},{"edgeType":"calls","source":353,"target":198},{"edgeType":"imports","source":833,"target":141},{"edgeType":"imports","source":873,"target":817},{"edgeType":"contains","source":27,"target":743},{"edgeType":"calls","source":175,"target":167},{"edgeType":"contains","source":49,"target":127},{"edgeType":"contains","source":151,"target":201},{"edgeType":"contains","source":207,"target":249},{"edgeType":"contains","source":146,"target":488},{"edgeType":"contains","source":937,"target":940},{"edgeType":"contains","source":840,"target":842},{"edgeType":"contains","source":679,"target":680},{"edgeType":"calls","source":195,"target":206},{"edgeType":"contains","source":102,"target":927},{"edgeType":"contains","source":551,"target":552},{"edgeType":"contains","source":879,"target":888},{"edgeType":"imports","source":873,"target":290},{"edgeType":"contains","source":297,"target":300},{"edgeType":"contains","source":2,"target":63},{"edgeType":"contains","source":555,"target":560},{"edgeType":"contains","source":113,"target":784},{"edgeType":"contains","source":113,"target":785},{"edgeType":"calls","source":408,"target":342},{"edgeType":"contains","source":745,"target":351},{"edgeType":"imports","source":873,"target":686},{"edgeType":"contains","source":136,"target":204},{"edgeType":"contains","source":138,"target":142},{"edgeType":"contains","source":25,"target":738},{"edgeType":"contains","source":791,"target":246},{"edgeType":"contains","source":25,"target":870},{"edgeType":"contains","source":49,"target":126},{"edgeType":"contains","source":102,"target":531},{"edgeType":"contains","source":318,"target":907},{"edgeType":"contains","source":555,"target":563},{"edgeType":"contains","source":589,"target":632},{"edgeType":"contains","source":237,"target":313},{"edgeType":"contains","source":207,"target":252},{"edgeType":"contains","source":713,"target":686},{"edgeType":"contains","source":88,"target":109},{"edgeType":"contains","source":237,"target":247},{"edgeType":"imports","source":102,"target":140},{"edgeType":"contains","source":146,"target":425},{"edgeType":"contains","source":454,"target":457},{"edgeType":"contains","source":580,"target":581},{"edgeType":"contains","source":297,"target":303},{"edgeType":"imports","source":348,"target":112},{"edgeType":"contains","source":146,"target":491},{"edgeType":"contains","source":753,"target":767},{"edgeType":"imports","source":873,"target":551},{"edgeType":"contains","source":525,"target":238},{"edgeType":"contains","source":745,"target":949},{"edgeType":"contains","source":324,"target":325},{"edgeType":"calls","source":164,"target":171},{"edgeType":"contains","source":4,"target":929},{"edgeType":"calls","source":418,"target":357},{"edgeType":"contains","source":880,"target":992},{"edgeType":"contains","source":99,"target":297},{"edgeType":"contains","source":928,"target":957},{"edgeType":"calls","source":373,"target":365},{"edgeType":"calls","source":774,"target":552},{"edgeType":"calls","source":179,"target":167},{"edgeType":"contains","source":207,"target":251},{"edgeType":"contains","source":98,"target":789},{"edgeType":"contains","source":146,"target":358},{"edgeType":"calls","source":975,"target":794},{"edgeType":"contains","source":146,"target":490},{"edgeType":"contains","source":454,"target":456},{"edgeType":"contains","source":748,"target":921},{"edgeType":"contains","source":297,"target":302},{"edgeType":"imports","source":102,"target":207},{"edgeType":"calls","source":267,"target":280},{"edgeType":"contains","source":555,"target":562},{"edgeType":"contains","source":421,"target":422},{"edgeType":"contains","source":37,"target":38},{"edgeType":"contains","source":668,"target":692},{"edgeType":"imports","source":113,"target":131},{"edgeType":"calls","source":288,"target":290},{"edgeType":"contains","source":8,"target":12},{"edgeType":"contains","source":25,"target":872},{"edgeType":"contains","source":713,"target":688},{"edgeType":"contains","source":98,"target":660},{"edgeType":"contains","source":146,"target":229},{"edgeType":"contains","source":589,"target":634},{"edgeType":"contains","source":297,"target":305},{"edgeType":"calls","source":354,"target":361},{"edgeType":"contains","source":27,"target":86},{"edgeType":"contains","source":4,"target":799},{"edgeType":"contains","source":146,"target":427},{"edgeType":"contains","source":642,"target":643},{"edgeType":"contains","source":580,"target":583},{"edgeType":"contains","source":514,"target":515},{"edgeType":"contains","source":146,"target":493},{"edgeType":"contains","source":454,"target":459},{"edgeType":"contains","source":809,"target":817},{"edgeType":"contains","source":745,"target":753},{"edgeType":"calls","source":837,"target":253},{"edgeType":"contains","source":949,"target":969},{"edgeType":"contains","source":2,"target":69},{"edgeType":"calls","source":377,"target":375},{"edgeType":"contains","source":6,"target":143},{"edgeType":"contains","source":660,"target":679},{"edgeType":"calls","source":177,"target":167},{"edgeType":"imports","source":348,"target":572},{"edgeType":"contains","source":760,"target":882},{"edgeType":"calls","source":611,"target":322},{"edgeType":"contains","source":713,"target":687},{"edgeType":"calls","source":837,"target":846},{"edgeType":"contains","source":237,"target":314},{"edgeType":"contains","source":2,"target":728},{"edgeType":"contains","source":867,"target":868},{"edgeType":"contains","source":98,"target":791},{"edgeType":"contains","source":151,"target":205},{"edgeType":"contains","source":146,"target":360},{"edgeType":"contains","source":932,"target":967},{"edgeType":"contains","source":146,"target":426},{"edgeType":"contains","source":753,"target":768},{"edgeType":"imports","source":348,"target":111},{"edgeType":"contains","source":146,"target":492},{"edgeType":"contains","source":145,"target":523},{"edgeType":"contains","source":580,"target":582},{"edgeType":"contains","source":453,"target":555},{"edgeType":"contains","source":4,"target":864},{"edgeType":"imports","source":873,"target":352},{"edgeType":"contains","source":454,"target":458},{"edgeType":"contains","source":551,"target":556},{"edgeType":"calls","source":191,"target":194},{"edgeType":"contains","source":352,"target":316},{"edgeType":"imports","source":873,"target":748},{"edgeType":"calls","source":156,"target":288},{"edgeType":"contains","source":880,"target":993},{"edgeType":"contains","source":6,"target":10},{"edgeType":"imports","source":660,"target":150},{"edgeType":"calls","source":763,"target":762},{"edgeType":"contains","source":25,"target":742},{"edgeType":"imports","source":348,"target":507},{"edgeType":"imports","source":873,"target":880},{"edgeType":"contains","source":25,"target":808},{"edgeType":"imports","source":932,"target":174},{"edgeType":"contains","source":932,"target":937},{"edgeType":"contains","source":679,"target":786},{"edgeType":"calls","source":278,"target":299},{"edgeType":"contains","source":146,"target":264},{"edgeType":"imports","source":809,"target":665},{"edgeType":"contains","source":151,"target":175},{"edgeType":"calls","source":267,"target":244},{"edgeType":"contains","source":146,"target":330},{"edgeType":"imports","source":873,"target":134},{"edgeType":"contains","source":840,"target":948},{"edgeType":"contains","source":748,"target":761},{"edgeType":"calls","source":167,"target":173},{"edgeType":"imports","source":348,"target":686},{"edgeType":"contains","source":96,"target":97},{"edgeType":"contains","source":311,"target":368},{"edgeType":"contains","source":2,"target":104},{"edgeType":"calls","source":355,"target":357},{"edgeType":"contains","source":25,"target":448},{"edgeType":"calls","source":408,"target":366},{"edgeType":"calls","source":247,"target":270},{"edgeType":"calls","source":768,"target":767},{"edgeType":"contains","source":593,"target":611},{"edgeType":"contains","source":760,"target":851},{"edgeType":"calls","source":675,"target":611},{"edgeType":"calls","source":609,"target":609},{"edgeType":"calls","source":719,"target":699},{"edgeType":"contains","source":527,"target":542},{"edgeType":"contains","source":146,"target":263},{"edgeType":"imports","source":873,"target":664},{"edgeType":"contains","source":146,"target":329},{"edgeType":"contains","source":37,"target":603},{"edgeType":"imports","source":348,"target":687},{"edgeType":"contains","source":7,"target":806},{"edgeType":"contains","source":385,"target":386},{"edgeType":"contains","source":2,"target":37},{"edgeType":"contains","source":129,"target":130},{"edgeType":"contains","source":7,"target":807},{"edgeType":"imports","source":809,"target":269},{"edgeType":"contains","source":7,"target":14},{"edgeType":"contains","source":311,"target":367},{"edgeType":"contains","source":748,"target":892},{"edgeType":"contains","source":531,"target":550},{"edgeType":"imports","source":873,"target":663},{"edgeType":"calls","source":412,"target":373},{"edgeType":"imports","source":873,"target":531},{"edgeType":"contains","source":453,"target":527},{"edgeType":"contains","source":895,"target":897},{"edgeType":"contains","source":146,"target":266},{"edgeType":"contains","source":352,"target":421},{"edgeType":"imports","source":809,"target":134},{"edgeType":"contains","source":151,"target":177},{"edgeType":"contains","source":146,"target":464},{"edgeType":"contains","source":339,"target":758},{"edgeType":"contains","source":286,"target":287},{"edgeType":"contains","source":7,"target":810},{"edgeType":"contains","source":129,"target":133},{"edgeType":"calls","source":959,"target":794},{"edgeType":"contains","source":311,"target":370},{"edgeType":"imports","source":348,"target":485},{"edgeType":"contains","source":5,"target":13},{"edgeType":"calls","source":408,"target":368},{"edgeType":"calls","source":180,"target":167},{"edgeType":"calls","source":695,"target":322},{"edgeType":"contains","source":679,"target":787},{"edgeType":"contains","source":551,"target":725},{"edgeType":"contains","source":831,"target":832},{"edgeType":"contains","source":959,"target":960},{"edgeType":"imports","source":809,"target":664},{"edgeType":"contains","source":963,"target":968},{"edgeType":"contains","source":146,"target":265},{"edgeType":"calls","source":395,"target":373},{"edgeType":"contains","source":146,"target":463},{"edgeType":"contains","source":25,"target":118},{"edgeType":"contains","source":385,"target":388},{"edgeType":"contains","source":352,"target":354},{"edgeType":"contains","source":339,"target":757},{"edgeType":"contains","source":2,"target":831},{"edgeType":"contains","source":63,"target":64},{"edgeType":"imports","source":879,"target":277},{"edgeType":"imports","source":873,"target":397},{"edgeType":"contains","source":113,"target":694},{"edgeType":"contains","source":98,"target":102},{"edgeType":"contains","source":745,"target":987},{"edgeType":"calls","source":357,"target":362},{"edgeType":"contains","source":311,"target":369},{"edgeType":"contains","source":564,"target":454},{"edgeType":"calls","source":408,"target":367},{"edgeType":"imports","source":873,"target":661},{"edgeType":"imports","source":809,"target":663},{"edgeType":"contains","source":451,"target":657},{"edgeType":"calls","source":427,"target":433},{"edgeType":"contains","source":352,"target":423},{"edgeType":"contains","source":573,"target":575},{"edgeType":"contains","source":151,"target":179},{"edgeType":"contains","source":146,"target":334},{"edgeType":"contains","source":286,"target":289},{"edgeType":"calls","source":173,"target":181},{"edgeType":"contains","source":337,"target":756},{"edgeType":"contains","source":833,"target":971},{"edgeType":"calls","source":355,"target":353},{"edgeType":"calls","source":326,"target":327},{"edgeType":"contains","source":146,"target":467},{"edgeType":"calls","source":397,"target":174},{"edgeType":"contains","source":745,"target":990},{"edgeType":"contains","source":713,"target":132},{"edgeType":"contains","source":34,"target":41},{"edgeType":"contains","source":745,"target":858},{"edgeType":"contains","source":698,"target":663},{"edgeType":"imports","source":668,"target":671},{"edgeType":"contains","source":809,"target":195},{"edgeType":"contains","source":91,"target":520},{"edgeType":"contains","source":7,"target":19},{"edgeType":"contains","source":698,"target":134},{"edgeType":"contains","source":893,"target":894},{"edgeType":"contains","source":573,"target":574},{"edgeType":"contains","source":98,"target":698},{"edgeType":"contains","source":146,"target":267},{"edgeType":"contains","source":352,"target":356},{"edgeType":"contains","source":840,"target":951},{"edgeType":"contains","source":151,"target":178},{"edgeType":"imports","source":701,"target":112},{"edgeType":"contains","source":61,"target":62},{"edgeType":"contains","source":146,"target":466},{"edgeType":"calls","source":388,"target":386},{"edgeType":"imports","source":102,"target":117},{"edgeType":"contains","source":713,"target":131},{"edgeType":"contains","source":745,"target":989},{"edgeType":"contains","source":668,"target":601},{"edgeType":"contains","source":629,"target":819},{"edgeType":"calls","source":768,"target":762},{"edgeType":"imports","source":348,"target":352},{"edgeType":"contains","source":760,"target":854},{"edgeType":"imports","source":873,"target":593},{"edgeType":"calls","source":561,"target":176},{"edgeType":"contains","source":880,"target":309},{"edgeType":"contains","source":348,"target":747},{"edgeType":"contains","source":25,"target":718},{"edgeType":"imports","source":879,"target":140},{"edgeType":"contains","source":339,"target":696},{"edgeType":"contains","source":833,"target":973},{"edgeType":"calls","source":363,"target":371},{"edgeType":"imports","source":99,"target":140},{"edgeType":"contains","source":286,"target":291},{"edgeType":"imports","source":668,"target":141},{"edgeType":"contains","source":98,"target":701},{"edgeType":"contains","source":27,"target":920},{"edgeType":"contains","source":410,"target":411},{"edgeType":"contains","source":151,"target":181},{"edgeType":"contains","source":146,"target":336},{"edgeType":"contains","source":98,"target":833},{"edgeType":"contains","source":90,"target":91},{"edgeType":"contains","source":119,"target":315},{"edgeType":"contains","source":745,"target":860},{"edgeType":"calls","source":357,"target":359},{"edgeType":"imports","source":833,"target":707},{"edgeType":"calls","source":196,"target":197},{"edgeType":"contains","source":840,"target":954},{"edgeType":"contains","source":698,"target":665},{"edgeType":"contains","source":551,"target":730},{"edgeType":"contains","source":113,"target":699},{"edgeType":"imports","source":348,"target":481},{"edgeType":"contains","source":879,"target":141},{"edgeType":"contains","source":451,"target":659},{"edgeType":"contains","source":963,"target":840},{"edgeType":"contains","source":643,"target":652},{"edgeType":"contains","source":833,"target":840},{"edgeType":"contains","source":352,"target":424},{"edgeType":"contains","source":955,"target":956},{"edgeType":"contains","source":668,"target":604},{"edgeType":"contains","source":573,"target":576},{"edgeType":"imports","source":99,"target":207},{"edgeType":"imports","source":698,"target":269},{"edgeType":"contains","source":151,"target":180},{"edgeType":"contains","source":412,"target":414},{"edgeType":"contains","source":833,"target":972},{"edgeType":"contains","source":23,"target":52},{"edgeType":"contains","source":146,"target":401},{"edgeType":"calls","source":975,"target":293},{"edgeType":"contains","source":745,"target":991},{"edgeType":"contains","source":146,"target":468},{"edgeType":"contains","source":949,"target":811},{"edgeType":"contains","source":91,"target":191},{"edgeType":"imports","source":348,"target":614},{"edgeType":"calls","source":262,"target":264},{"edgeType":"imports","source":879,"target":207},{"edgeType":"contains","source":745,"target":793},{"edgeType":"contains","source":698,"target":664},{"edgeType":"contains","source":25,"target":321},{"edgeType":"contains","source":91,"target":590},{"edgeType":"imports","source":113,"target":117},{"edgeType":"contains","source":643,"target":655},{"edgeType":"contains","source":825,"target":827},{"edgeType":"imports","source":348,"target":694},{"edgeType":"contains","source":728,"target":729},{"edgeType":"contains","source":937,"target":460},{"edgeType":"calls","source":858,"target":875},{"edgeType":"contains","source":668,"target":607},{"edgeType":"contains","source":344,"target":345},{"edgeType":"contains","source":668,"target":673},{"edgeType":"contains","source":573,"target":579},{"edgeType":"imports","source":809,"target":673},{"edgeType":"contains","source":88,"target":89},{"edgeType":"contains","source":91,"target":194},{"edgeType":"contains","source":745,"target":994},{"edgeType":"contains","source":551,"target":732},{"edgeType":"imports","source":660,"target":140},{"edgeType":"contains","source":701,"target":706},{"edgeType":"contains","source":643,"target":654},{"edgeType":"contains","source":69,"target":346},{"edgeType":"contains","source":6,"target":317},{"edgeType":"imports","source":145,"target":117},{"edgeType":"calls","source":449,"target":406},{"edgeType":"calls","source":220,"target":238},{"edgeType":"imports","source":745,"target":280},{"edgeType":"contains","source":825,"target":826},{"edgeType":"contains","source":453,"target":136},{"edgeType":"contains","source":286,"target":292},{"edgeType":"contains","source":660,"target":788},{"edgeType":"contains","source":809,"target":661},{"edgeType":"calls","source":994,"target":754},{"edgeType":"contains","source":339,"target":697},{"edgeType":"calls","source":478,"target":168},{"edgeType":"contains","source":573,"target":578},{"edgeType":"imports","source":873,"target":672},{"edgeType":"contains","source":151,"target":182},{"edgeType":"contains","source":151,"target":183},{"edgeType":"contains","source":23,"target":55},{"edgeType":"imports","source":91,"target":140},{"edgeType":"contains","source":146,"target":470},{"edgeType":"calls","source":396,"target":398},{"edgeType":"calls","source":171,"target":172},{"edgeType":"contains","source":2,"target":45},{"edgeType":"contains","source":7,"target":815},{"edgeType":"contains","source":748,"target":900},{"edgeType":"contains","source":352,"target":429},{"edgeType":"imports","source":873,"target":669},{"edgeType":"contains","source":760,"target":862},{"edgeType":"contains","source":698,"target":670},{"edgeType":"calls","source":442,"target":428},{"edgeType":"contains","source":823,"target":825},{"edgeType":"contains","source":286,"target":295},{"edgeType":"contains","source":311,"target":379},{"edgeType":"contains","source":543,"target":454},{"edgeType":"contains","source":668,"target":609},{"edgeType":"contains","source":86,"target":87},{"edgeType":"calls","source":328,"target":329},{"edgeType":"imports","source":91,"target":269},{"edgeType":"contains","source":151,"target":186},{"edgeType":"contains","source":146,"target":407},{"edgeType":"calls","source":330,"target":333},{"edgeType":"contains","source":748,"target":903},{"edgeType":"imports","source":660,"target":665},{"edgeType":"calls","source":377,"target":394},{"edgeType":"contains","source":99,"target":277},{"edgeType":"calls","source":601,"target":387},{"edgeType":"imports","source":873,"target":670},{"edgeType":"contains","source":760,"target":861},{"edgeType":"contains","source":91,"target":591},{"edgeType":"contains","source":698,"target":669},{"edgeType":"contains","source":643,"target":656},{"edgeType":"contains","source":286,"target":294},{"edgeType":"contains","source":759,"target":760},{"edgeType":"imports","source":348,"target":693},{"edgeType":"contains","source":88,"target":816},{"edgeType":"contains","source":932,"target":880},{"edgeType":"calls","source":399,"target":373},{"edgeType":"contains","source":660,"target":790},{"edgeType":"contains","source":311,"target":312},{"edgeType":"contains","source":311,"target":378},{"edgeType":"contains","source":473,"target":509},{"edgeType":"contains","source":25,"target":919},{"edgeType":"contains","source":146,"target":273},{"edgeType":"calls","source":394,"target":264},{"edgeType":"contains","source":119,"target":120},{"edgeType":"imports","source":873,"target":207},{"edgeType":"contains","source":151,"target":185},{"edgeType":"contains","source":2,"target":642},{"edgeType":"imports","source":873,"target":141},{"edgeType":"contains","source":146,"target":406},{"edgeType":"contains","source":146,"target":472},{"edgeType":"contains","source":551,"target":733},{"edgeType":"contains","source":748,"target":902},{"edgeType":"contains","source":2,"target":47},{"edgeType":"contains","source":5,"target":23},{"edgeType":"contains","source":352,"target":365},{"edgeType":"contains","source":698,"target":672},{"edgeType":"contains","source":352,"target":431},{"edgeType":"imports","source":809,"target":669},{"edgeType":"contains","source":136,"target":190},{"edgeType":"contains","source":91,"target":594},{"edgeType":"contains","source":25,"target":724},{"edgeType":"contains","source":27,"target":662},{"edgeType":"imports","source":348,"target":690},{"edgeType":"contains","source":473,"target":512},{"edgeType":"contains","source":404,"target":405},{"edgeType":"contains","source":668,"target":280},{"edgeType":"contains","source":7,"target":622},{"edgeType":"contains","source":146,"target":409},{"edgeType":"contains","source":146,"target":475},{"edgeType":"contains","source":297,"target":286},{"edgeType":"imports","source":660,"target":663},{"edgeType":"contains","source":98,"target":113},{"edgeType":"contains","source":352,"target":364},{"edgeType":"calls","source":852,"target":858},{"edgeType":"contains","source":352,"target":430},{"edgeType":"contains","source":955,"target":962},{"edgeType":"contains","source":286,"target":296},{"edgeType":"imports","source":348,"target":691},{"edgeType":"contains","source":949,"target":950},{"edgeType":"contains","source":629,"target":630},{"edgeType":"contains","source":473,"target":511},{"edgeType":"contains","source":151,"target":187},{"edgeType":"calls","source":273,"target":309},{"edgeType":"contains","source":2,"target":710},{"edgeType":"contains","source":748,"target":904},{"edgeType":"contains","source":6,"target":916},{"edgeType":"imports","source":660,"target":664},{"edgeType":"contains","source":809,"target":206},{"edgeType":"imports","source":873,"target":665},{"edgeType":"contains","source":311,"target":383},{"edgeType":"imports","source":348,"target":688},{"edgeType":"contains","source":91,"target":596},{"edgeType":"contains","source":25,"target":726},{"edgeType":"contains","source":402,"target":403},{"edgeType":"contains","source":698,"target":674},{"edgeType":"contains","source":713,"target":671},{"edgeType":"imports","source":102,"target":122},{"edgeType":"calls","source":970,"target":969},{"edgeType":"contains","source":7,"target":624},{"edgeType":"contains","source":146,"target":477},{"edgeType":"imports","source":660,"target":661},{"edgeType":"calls","source":842,"target":841},{"edgeType":"calls","source":425,"target":357},{"edgeType":"imports","source":113,"target":111},{"edgeType":"contains","source":453,"target":473},{"edgeType":"contains","source":91,"target":397},{"edgeType":"contains","source":627,"target":628},{"edgeType":"contains","source":13,"target":40},{"edgeType":"calls","source":483,"target":407},{"edgeType":"contains","source":311,"target":382},{"edgeType":"imports","source":660,"target":134},{"edgeType":"calls","source":615,"target":610},{"edgeType":"contains","source":451,"target":798},{"edgeType":"contains","source":589,"target":616},{"edgeType":"calls","source":980,"target":460},{"edgeType":"imports","source":873,"target":269},{"edgeType":"contains","source":535,"target":374},{"edgeType":"contains","source":104,"target":721},{"edgeType":"contains","source":7,"target":821},{"edgeType":"contains","source":451,"target":666},{"edgeType":"contains","source":352,"target":432},{"edgeType":"contains","source":748,"target":774},{"edgeType":"contains","source":7,"target":755},{"edgeType":"contains","source":156,"target":268},{"edgeType":"contains","source":627,"target":796},{"edgeType":"contains","source":880,"target":881},{"edgeType":"contains","source":603,"target":615},{"edgeType":"contains","source":45,"target":934},{"edgeType":"contains","source":589,"target":653},{"edgeType":"imports","source":348,"target":207},{"edgeType":"contains","source":98,"target":348},{"edgeType":"contains","source":593,"target":595},{"edgeType":"contains","source":698,"target":709},{"edgeType":"imports","source":348,"target":141},{"edgeType":"contains","source":679,"target":769},{"edgeType":"contains","source":146,"target":248},{"edgeType":"calls","source":530,"target":168},{"edgeType":"contains","source":98,"target":745},{"edgeType":"contains","source":151,"target":225},{"edgeType":"contains","source":146,"target":380},{"edgeType":"calls","source":694,"target":699},{"edgeType":"imports","source":873,"target":117},{"edgeType":"contains","source":25,"target":101},{"edgeType":"contains","source":385,"target":436},{"edgeType":"contains","source":352,"target":402},{"edgeType":"contains","source":7,"target":922},{"edgeType":"contains","source":981,"target":986},{"edgeType":"contains","source":531,"target":534},{"edgeType":"contains","source":277,"target":282},{"edgeType":"contains","source":337,"target":338},{"edgeType":"contains","source":564,"target":568},{"edgeType":"contains","source":698,"target":708},{"edgeType":"calls","source":404,"target":373},{"edgeType":"contains","source":17,"target":18},{"edgeType":"contains","source":453,"target":573},{"edgeType":"calls","source":372,"target":374},{"edgeType":"calls","source":847,"target":844},{"edgeType":"calls","source":877,"target":839},{"edgeType":"contains","source":589,"target":651},{"edgeType":"contains","source":7,"target":658},{"edgeType":"contains","source":151,"target":224},{"edgeType":"imports","source":348,"target":604},{"edgeType":"imports","source":348,"target":601},{"edgeType":"contains","source":33,"target":53},{"edgeType":"contains","source":277,"target":285},{"edgeType":"contains","source":7,"target":925},{"edgeType":"contains","source":603,"target":617},{"edgeType":"contains","source":527,"target":529},{"edgeType":"contains","source":531,"target":537},{"edgeType":"contains","source":564,"target":571},{"edgeType":"contains","source":99,"target":385},{"edgeType":"contains","source":237,"target":270},{"edgeType":"contains","source":25,"target":830},{"edgeType":"contains","source":679,"target":771},{"edgeType":"imports","source":91,"target":112},{"edgeType":"contains","source":352,"target":404},{"edgeType":"contains","source":745,"target":839},{"edgeType":"contains","source":151,"target":161},{"edgeType":"calls","source":360,"target":353},{"edgeType":"contains","source":151,"target":227},{"edgeType":"contains","source":98,"target":879},{"edgeType":"imports","source":745,"target":253},{"edgeType":"contains","source":64,"target":82},{"edgeType":"contains","source":2,"target":88},{"edgeType":"calls","source":388,"target":342},{"edgeType":"contains","source":277,"target":284},{"edgeType":"contains","source":668,"target":253},{"edgeType":"contains","source":4,"target":92},{"edgeType":"calls","source":310,"target":316},{"edgeType":"imports","source":348,"target":140},{"edgeType":"contains","source":399,"target":400},{"edgeType":"contains","source":760,"target":770},{"edgeType":"contains","source":564,"target":570},{"edgeType":"contains","source":79,"target":80},{"edgeType":"calls","source":994,"target":253},{"edgeType":"contains","source":385,"target":437},{"edgeType":"contains","source":151,"target":160},{"edgeType":"contains","source":151,"target":226},{"edgeType":"contains","source":146,"target":381},{"edgeType":"calls","source":591,"target":590},{"edgeType":"imports","source":932,"target":269},{"edgeType":"contains","source":753,"target":792},{"edgeType":"contains","source":145,"target":613},{"edgeType":"calls","source":605,"target":613},{"edgeType":"contains","source":2,"target":25},{"edgeType":"contains","source":909,"target":911},{"edgeType":"contains","source":791,"target":803},{"edgeType":"contains","source":207,"target":211},{"edgeType":"contains","source":269,"target":271},{"edgeType":"calls","source":449,"target":428},{"edgeType":"imports","source":348,"target":269},{"edgeType":"imports","source":145,"target":352},{"edgeType":"calls","source":408,"target":378},{"edgeType":"contains","source":13,"target":81},{"edgeType":"contains","source":151,"target":163},{"edgeType":"calls","source":229,"target":244},{"edgeType":"contains","source":4,"target":94},{"edgeType":"contains","source":527,"target":530},{"edgeType":"contains","source":2,"target":90},{"edgeType":"contains","source":525,"target":526},{"edgeType":"contains","source":207,"target":210},{"edgeType":"contains","source":531,"target":538},{"edgeType":"contains","source":77,"target":78},{"edgeType":"contains","source":748,"target":483},{"edgeType":"contains","source":555,"target":454},{"edgeType":"contains","source":679,"target":772},{"edgeType":"imports","source":873,"target":246},{"edgeType":"contains","source":385,"target":439},{"edgeType":"contains","source":151,"target":162},{"edgeType":"contains","source":151,"target":228},{"edgeType":"contains","source":146,"target":449},{"edgeType":"contains","source":151,"target":231},{"edgeType":"calls","source":421,"target":373},{"edgeType":"imports","source":932,"target":793},{"edgeType":"contains","source":146,"target":518},{"edgeType":"contains","source":748,"target":751},{"edgeType":"imports","source":809,"target":708},{"edgeType":"contains","source":2,"target":27},{"edgeType":"contains","source":136,"target":168},{"edgeType":"contains","source":7,"target":71},{"edgeType":"contains","source":793,"target":941},{"edgeType":"contains","source":453,"target":580},{"edgeType":"contains","source":453,"target":514},{"edgeType":"contains","source":79,"target":85},{"edgeType":"contains","source":146,"target":188},{"edgeType":"contains","source":151,"target":165},{"edgeType":"contains","source":91,"target":174},{"edgeType":"contains","source":146,"target":517},{"edgeType":"contains","source":104,"target":828},{"edgeType":"contains","source":748,"target":750},{"edgeType":"contains","source":715,"target":716},{"edgeType":"contains","source":525,"target":528},{"edgeType":"contains","source":207,"target":212},{"edgeType":"imports","source":891,"target":83},{"edgeType":"calls","source":449,"target":363},{"edgeType":"calls","source":752,"target":483},{"edgeType":"imports","source":873,"target":707},{"edgeType":"contains","source":385,"target":441},{"edgeType":"imports","source":873,"target":244},{"edgeType":"contains","source":151,"target":164},{"edgeType":"contains","source":151,"target":230},{"edgeType":"contains","source":833,"target":955},{"edgeType":"contains","source":151,"target":167},{"edgeType":"contains","source":146,"target":322},{"edgeType":"contains","source":104,"target":633},{"edgeType":"contains","source":745,"target":846},{"edgeType":"calls","source":363,"target":381},{"edgeType":"contains","source":2,"target":822},{"edgeType":"contains","source":269,"target":275},{"edgeType":"imports","source":102,"target":111},{"edgeType":"contains","source":7,"target":73},{"edgeType":"contains","source":793,"target":943},{"edgeType":"contains","source":352,"target":476},{"edgeType":"contains","source":104,"target":105},{"edgeType":"contains","source":136,"target":170},{"edgeType":"contains","source":760,"target":843},{"edgeType":"calls","source":381,"target":418},{"edgeType":"contains","source":593,"target":272},{"edgeType":"contains","source":77,"target":83},{"edgeType":"contains","source":352,"target":410},{"edgeType":"contains","source":627,"target":936},{"edgeType":"contains","source":146,"target":256},{"edgeType":"contains","source":25,"target":108},{"edgeType":"contains","source":146,"target":387},{"edgeType":"calls","source":881,"target":442},{"edgeType":"contains","source":909,"target":914},{"edgeType":"contains","source":748,"target":752},{"edgeType":"contains","source":91,"target":176},{"edgeType":"contains","source":146,"target":519},{"edgeType":"contains","source":713,"target":714},{"edgeType":"contains","source":145,"target":682},{"edgeType":"contains","source":269,"target":274},{"edgeType":"contains","source":6,"target":36},{"edgeType":"contains","source":136,"target":169},{"edgeType":"contains","source":137,"target":138},{"edgeType":"contains","source":7,"target":72},{"edgeType":"contains","source":793,"target":942},{"edgeType":"contains","source":385,"target":443},{"edgeType":"contains","source":760,"target":776},{"edgeType":"contains","source":385,"target":311},{"edgeType":"contains","source":145,"target":220},{"edgeType":"contains","source":25,"target":901},{"edgeType":"contains","source":146,"target":255},{"edgeType":"contains","source":629,"target":939},{"edgeType":"contains","source":151,"target":166},{"edgeType":"contains","source":146,"target":258},{"edgeType":"contains","source":713,"target":717},{"edgeType":"contains","source":593,"target":605},{"edgeType":"calls","source":605,"target":611},{"edgeType":"contains","source":237,"target":278},{"edgeType":"imports","source":99,"target":136},{"edgeType":"imports","source":932,"target":277},{"edgeType":"calls","source":418,"target":264},{"edgeType":"contains","source":7,"target":801},{"edgeType":"contains","source":37,"target":928},{"edgeType":"imports","source":668,"target":269},{"edgeType":"contains","source":7,"target":9},{"edgeType":"contains","source":352,"target":412},{"edgeType":"contains","source":2,"target":98},{"edgeType":"contains","source":760,"target":845},{"edgeType":"calls","source":722,"target":552},{"edgeType":"contains","source":7,"target":75},{"edgeType":"calls","source":428,"target":483},{"edgeType":"contains","source":713,"target":122},{"edgeType":"contains","source":627,"target":740},{"edgeType":"imports","source":348,"target":609},{"edgeType":"contains","source":7,"target":602},{"edgeType":"contains","source":25,"target":44},{"edgeType":"contains","source":27,"target":114},{"edgeType":"contains","source":207,"target":216},{"edgeType":"calls","source":267,"target":253},{"edgeType":"imports","source":99,"target":269},{"edgeType":"contains","source":7,"target":800},{"edgeType":"contains","source":2,"target":96},{"edgeType":"calls","source":994,"target":244},{"edgeType":"contains","source":37,"target":68},{"edgeType":"contains","source":7,"target":74},{"edgeType":"contains","source":793,"target":944},{"edgeType":"contains","source":77,"target":84},{"edgeType":"contains","source":25,"target":639},{"edgeType":"contains","source":713,"target":121},{"edgeType":"contains","source":286,"target":277},{"edgeType":"contains","source":49,"target":93},{"edgeType":"contains","source":146,"target":257},{"edgeType":"contains","source":146,"target":260},{"edgeType":"contains","source":146,"target":326},{"edgeType":"contains","source":527,"target":539},{"edgeType":"contains","source":740,"target":741},{"edgeType":"contains","source":833,"target":963},{"edgeType":"calls","source":156,"target":188},{"edgeType":"imports","source":809,"target":520},{"edgeType":"calls","source":190,"target":191},{"edgeType":"imports","source":348,"target":607},{"edgeType":"contains","source":531,"target":547},{"edgeType":"contains","source":352,"target":150},{"edgeType":"contains","source":27,"target":712},{"edgeType":"contains","source":793,"target":947},{"edgeType":"calls","source":408,"target":370},{"edgeType":"contains","source":102,"target":501},{"edgeType":"contains","source":23,"target":42},{"edgeType":"contains","source":146,"target":259},{"edgeType":"imports","source":873,"target":189},{"edgeType":"contains","source":2,"target":627},{"edgeType":"contains","source":119,"target":237},{"edgeType":"contains","source":2,"target":759},{"edgeType":"contains","source":348,"target":736},{"edgeType":"contains","source":453,"target":454},{"edgeType":"contains","source":745,"target":981},{"edgeType":"contains","source":389,"target":390},{"edgeType":"contains","source":453,"target":586},{"edgeType":"contains","source":69,"target":70},{"edgeType":"imports","source":879,"target":531},{"edgeType":"contains","source":760,"target":780},{"edgeType":"contains","source":91,"target":577},{"edgeType":"calls","source":609,"target":612},{"edgeType":"calls","source":408,"target":369},{"edgeType":"calls","source":375,"target":401},{"edgeType":"calls","source":410,"target":373},{"edgeType":"contains","source":102,"target":500},{"edgeType":"contains","source":49,"target":95},{"edgeType":"contains","source":551,"target":722},{"edgeType":"contains","source":146,"target":262},{"edgeType":"contains","source":146,"target":328},{"edgeType":"contains","source":151,"target":173},{"edgeType":"imports","source":873,"target":120},{"edgeType":"imports","source":453,"target":191},{"edgeType":"contains","source":146,"target":394},{"edgeType":"contains","source":25,"target":115},{"edgeType":"contains","source":7,"target":805},{"edgeType":"contains","source":352,"target":417},{"edgeType":"contains","source":745,"target":852},{"edgeType":"contains","source":98,"target":99},{"edgeType":"imports","source":809,"target":782},{"edgeType":"contains","source":809,"target":189},{"edgeType":"contains","source":38,"target":43},{"edgeType":"contains","source":27,"target":450},{"edgeType":"calls","source":188,"target":189},{"edgeType":"contains","source":531,"target":549},{"edgeType":"imports","source":348,"target":671},{"edgeType":"contains","source":311,"target":366},{"edgeType":"contains","source":593,"target":675},{"edgeType":"imports","source":932,"target":140},{"edgeType":"contains","source":760,"target":849},{"edgeType":"contains","source":2,"target":629},{"edgeType":"contains","source":589,"target":600},{"edgeType":"calls","source":178,"target":167},{"edgeType":"imports","source":873,"target":253},{"edgeType":"calls","source":463,"target":449},{"edgeType":"contains","source":146,"target":327},{"edgeType":"contains","source":527,"target":540},{"edgeType":"contains","source":748,"target":890},{"edgeType":"contains","source":2,"target":893},{"edgeType":"contains","source":451,"target":452},{"edgeType":"calls","source":389,"target":365},{"edgeType":"contains","source":323,"target":324},{"edgeType":"contains","source":7,"target":804},{"edgeType":"imports","source":873,"target":385},{"edgeType":"calls","source":852,"target":877},{"edgeType":"contains","source":352,"target":415},{"edgeType":"contains","source":531,"target":548}],"nodes":[{"groupName":"","id":2,"nodeType":"Repo","repoName":"pallets#flask#d8c37f43724cd9fb0870f77877b7c4c7e38a19e0"},{"id":4,"name":"docs/tutorial","nodeType":"Package"},{"id":5,"name":"tests/test_apps/cliapp","nodeType":"Package"},{"id":6,"name":"requirements","nodeType":"Package"},{"id":7,"name":"docs","nodeType":"Package"},{"id":8,"name":".github","nodeType":"Package"},{"id":9,"name":"extensiondev.rst","nodeType":"TextFile","path":"docs","text":"Flask Extension Development\n===========================\n\nFlask, being a microframework, often requires some repetitive steps to get\na third party library working. Many such extensions are already available\non `PyPI`_.\n\nIf you want to create your own Flask extension for something that does not\nexist yet, this guide to extension development will help you get your\nextension running in no time and to feel like users would expect your\nextension to behave.\n\nAnatomy of an Extension\n-----------------------\n\nExtensions are all located in a package called ``flask_something``\nwhere \"something\" is the name of the library you want to bridge. So for\nexample if you plan to add support for a library named `simplexml` to\nFlask, you would name your extension's package ``flask_simplexml``.\n\nThe name of the actual extension (the human readable name) however would\nbe something like \"Flask-SimpleXML\". Make sure to include the name\n\"Flask\" somewhere in that name and that you check the capitalization.\nThis is how users can then register dependencies to your extension in\ntheir :file:`setup.py` files.\n\nBut what do extensions look like themselves? An extension has to ensure\nthat it works with multiple Flask application instances at once. This is\na requirement because many people will use patterns like the\n:doc:`/patterns/appfactories` pattern to create their application as\nneeded to aid unittests and to support multiple configurations. Because\nof that it is crucial that your application supports that kind of\nbehavior.\n\nMost importantly the extension must be shipped with a :file:`setup.py` file and\nregistered on PyPI. Also the development checkout link should work so\nthat people can easily install the development version into their\nvirtualenv without having to download the library by hand.\n\nFlask extensions must be licensed under a BSD, MIT or more liberal license\nin order to be listed in the Flask Extension Registry. Keep in mind\nthat the Flask Extension Registry is a moderated place and libraries will\nbe reviewed upfront if they behave as required.\n\n\"Hello Flaskext!\"\n-----------------\n\nSo let's get started with creating such a Flask extension. The extension\nwe want to create here will provide very basic support for SQLite3.\n\nFirst we create the following folder structure::\n\n flask-sqlite3/\n flask_sqlite3.py\n LICENSE\n README\n\nHere's the contents of the most important files:\n\nsetup.py\n````````\n\nThe next file that is absolutely required is the :file:`setup.py` file which is\nused to install your Flask extension. The following contents are\nsomething you can work with::\n\n \"\"\"\n Flask-SQLite3\n -------------\n\n This is the description for that library\n \"\"\"\n from setuptools import setup\n\n\n setup(\n name='Flask-SQLite3',\n version='1.0',\n url='http://example.com/flask-sqlite3/',\n license='BSD',\n author='Your Name',\n author_email='your-email@example.com',\n description='Very short description',\n long_description=__doc__,\n py_modules=['flask_sqlite3'],\n # if you would be using a package instead use packages instead\n # of py_modules:\n # packages=['flask_sqlite3'],\n zip_safe=False,\n include_package_data=True,\n platforms='any',\n install_requires=[\n 'Flask'\n ],\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n )\n\nThat's a lot of code but you can really just copy/paste that from existing\nextensions and adapt.\n\nflask_sqlite3.py\n````````````````\n\nNow this is where your extension code goes. But how exactly should such\nan extension look like? What are the best practices? Continue reading\nfor some insight.\n\nInitializing Extensions\n-----------------------\n\nMany extensions will need some kind of initialization step. For example,\nconsider an application that's currently connecting to SQLite like the\ndocumentation suggests (:doc:`/patterns/sqlite3`). So how does the\nextension know the name of the application object?\n\nQuite simple: you pass it to it.\n\nThere are two recommended ways for an extension to initialize:\n\ninitialization functions:\n\n If your extension is called `helloworld` you might have a function\n called ``init_helloworld(app[, extra_args])`` that initializes the\n extension for that application. It could attach before / after\n handlers etc.\n\nclasses:\n\n Classes work mostly like initialization functions but can later be\n used to further change the behavior.\n\nWhat to use depends on what you have in mind. For the SQLite 3 extension\nwe will use the class-based approach because it will provide users with an\nobject that handles opening and closing database connections.\n\nWhen designing your classes, it's important to make them easily reusable\nat the module level. This means the object itself must not under any\ncircumstances store any application specific state and must be shareable\nbetween different applications.\n\nThe Extension Code\n------------------\n\nHere's the contents of the `flask_sqlite3.py` for copy/paste::\n\n import sqlite3\n from flask import current_app, _app_ctx_stack\n\n\n class SQLite3(object):\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n app.config.setdefault('SQLITE3_DATABASE', ':memory:')\n app.teardown_appcontext(self.teardown)\n\n def connect(self):\n return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'sqlite3_db'):\n ctx.sqlite3_db.close()\n\n @property\n def connection(self):\n ctx = _app_ctx_stack.top\n if ctx is not None:\n if not hasattr(ctx, 'sqlite3_db'):\n ctx.sqlite3_db = self.connect()\n return ctx.sqlite3_db\n\n\nSo here's what these lines of code do:\n\n1. The ``__init__`` method takes an optional app object and, if supplied, will\n call ``init_app``.\n2. The ``init_app`` method exists so that the ``SQLite3`` object can be\n instantiated without requiring an app object. This method supports the\n factory pattern for creating applications. The ``init_app`` will set the\n configuration for the database, defaulting to an in memory database if\n no configuration is supplied. In addition, the ``init_app`` method\n attaches the ``teardown`` handler.\n3. Next, we define a ``connect`` method that opens a database connection.\n4. Finally, we add a ``connection`` property that on first access opens\n the database connection and stores it on the context. This is also\n the recommended way to handling resources: fetch resources lazily the\n first time they are used.\n\n Note here that we're attaching our database connection to the top\n application context via ``_app_ctx_stack.top``. Extensions should use\n the top context for storing their own information with a sufficiently\n complex name.\n\nSo why did we decide on a class-based approach here? Because using our\nextension looks something like this::\n\n from flask import Flask\n from flask_sqlite3 import SQLite3\n\n app = Flask(__name__)\n app.config.from_pyfile('the-config.cfg')\n db = SQLite3(app)\n\nYou can then use the database from views like this::\n\n @app.route('/')\n def show_all():\n cur = db.connection.cursor()\n cur.execute(...)\n\nLikewise if you are outside of a request you can use the database by\npushing an app context::\n\n with app.app_context():\n cur = db.connection.cursor()\n cur.execute(...)\n\nAt the end of the ``with`` block the teardown handles will be executed\nautomatically.\n\nAdditionally, the ``init_app`` method is used to support the factory pattern\nfor creating apps::\n\n db = SQLite3()\n # Then later on.\n app = create_app('the-config.cfg')\n db.init_app(app)\n\nKeep in mind that supporting this factory pattern for creating apps is required\nfor approved flask extensions (described below).\n\n.. admonition:: Note on ``init_app``\n\n As you noticed, ``init_app`` does not assign ``app`` to ``self``. This\n is intentional! Class based Flask extensions must only store the\n application on the object when the application was passed to the\n constructor. This tells the extension: I am not interested in using\n multiple applications.\n\n When the extension needs to find the current application and it does\n not have a reference to it, it must either use the\n :data:`~flask.current_app` context local or change the API in a way\n that you can pass the application explicitly.\n\n\nUsing _app_ctx_stack\n--------------------\n\nIn the example above, before every request, a ``sqlite3_db`` variable is\nassigned to ``_app_ctx_stack.top``. In a view function, this variable is\naccessible using the ``connection`` property of ``SQLite3``. During the\nteardown of a request, the ``sqlite3_db`` connection is closed. By using\nthis pattern, the *same* connection to the sqlite3 database is accessible\nto anything that needs it for the duration of the request.\n\n\nLearn from Others\n-----------------\n\nThis documentation only touches the bare minimum for extension development.\nIf you want to learn more, it's a very good idea to check out existing extensions\non the `PyPI`_. If you feel lost there is still the `mailinglist`_ and the\n`Discord server`_ to get some ideas for nice looking APIs. Especially if you do\nsomething nobody before you did, it might be a very good idea to get some more\ninput. This not only generates useful feedback on what people might want from\nan extension, but also avoids having multiple developers working in isolation\non pretty much the same problem.\n\nRemember: good API design is hard, so introduce your project on the\nmailing list, and let other developers give you a helping hand with\ndesigning the API.\n\nThe best Flask extensions are extensions that share common idioms for the\nAPI. And this can only work if collaboration happens early.\n\nApproved Extensions\n-------------------\n\nFlask previously had the concept of approved extensions. These came with\nsome vetting of support and compatibility. While this list became too\ndifficult to maintain over time, the guidelines are still relevant to\nall extensions maintained and developed today, as they help the Flask\necosystem remain consistent and compatible.\n\n0. An approved Flask extension requires a maintainer. In the event an\n extension author would like to move beyond the project, the project\n should find a new maintainer and transfer access to the repository,\n documentation, PyPI, and any other services. If no maintainer\n is available, give access to the Pallets core team.\n1. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.\n It must provide exactly one package or module named\n ``flask_extension_name``.\n2. The extension must be BSD or MIT licensed. It must be open source\n and publicly available.\n3. The extension's API must have the following characteristics:\n\n - It must support multiple applications running in the same Python\n process. Use ``current_app`` instead of ``self.app``, store\n configuration and state per application instance.\n - It must be possible to use the factory pattern for creating\n applications. Use the ``ext.init_app()`` pattern.\n\n4. From a clone of the repository, an extension with its dependencies\n must be installable with ``pip install -e .``.\n5. It must ship a testing suite that can be invoked with ``tox -e py``\n or ``pytest``. If not using ``tox``, the test dependencies should be\n specified in a ``requirements.txt`` file. The tests must be part of\n the sdist distribution.\n6. The documentation must use the ``flask`` theme from the\n `Official Pallets Themes`_. A link to the documentation or project\n website must be in the PyPI metadata or the readme.\n7. For maximum compatibility, the extension should support the same\n versions of Python that Flask supports. 3.6+ is recommended as of\n 2020. Use ``python_requires=\">= 3.6\"`` in ``setup.py`` to indicate\n supported versions.\n\n.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask\n.. _mailinglist: https://mail.python.org/mailman/listinfo/flask\n.. _Discord server: https://discord.gg/pallets\n.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/\n"},{"id":10,"name":"tests.in","nodeType":"TextFile","path":"requirements","text":"pytest\nasgiref\nblinker\ngreenlet\npython-dotenv\n"},{"id":11,"name":"factory.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nApplication Setup\n=================\n\nA Flask application is an instance of the :class:`Flask` class.\nEverything about the application, such as configuration and URLs, will\nbe registered with this class.\n\nThe most straightforward way to create a Flask application is to create\na global :class:`Flask` instance directly at the top of your code, like\nhow the \"Hello, World!\" example did on the previous page. While this is\nsimple and useful in some cases, it can cause some tricky issues as the\nproject grows.\n\nInstead of creating a :class:`Flask` instance globally, you will create\nit inside a function. This function is known as the *application\nfactory*. Any configuration, registration, and other setup the\napplication needs will happen inside the function, then the application\nwill be returned.\n\n\nThe Application Factory\n-----------------------\n\nIt's time to start coding! Create the ``flaskr`` directory and add the\n``__init__.py`` file. The ``__init__.py`` serves double duty: it will\ncontain the application factory, and it tells Python that the ``flaskr``\ndirectory should be treated as a package.\n\n.. code-block:: none\n\n $ mkdir flaskr\n\n.. code-block:: python\n :caption: ``flaskr/__init__.py``\n\n import os\n\n from flask import Flask\n\n\n def create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='dev',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n # a simple page that says hello\n @app.route('/hello')\n def hello():\n return 'Hello, World!'\n\n return app\n\n``create_app`` is the application factory function. You'll add to it\nlater in the tutorial, but it already does a lot.\n\n#. ``app = Flask(__name__, instance_relative_config=True)`` creates the\n :class:`Flask` instance.\n\n * ``__name__`` is the name of the current Python module. The app\n needs to know where it's located to set up some paths, and\n ``__name__`` is a convenient way to tell it that.\n\n * ``instance_relative_config=True`` tells the app that\n configuration files are relative to the\n :ref:`instance folder `. The instance folder\n is located outside the ``flaskr`` package and can hold local\n data that shouldn't be committed to version control, such as\n configuration secrets and the database file.\n\n#. :meth:`app.config.from_mapping() ` sets\n some default configuration that the app will use:\n\n * :data:`SECRET_KEY` is used by Flask and extensions to keep data\n safe. It's set to ``'dev'`` to provide a convenient value\n during development, but it should be overridden with a random\n value when deploying.\n\n * ``DATABASE`` is the path where the SQLite database file will be\n saved. It's under\n :attr:`app.instance_path `, which is the\n path that Flask has chosen for the instance folder. You'll learn\n more about the database in the next section.\n\n#. :meth:`app.config.from_pyfile() ` overrides\n the default configuration with values taken from the ``config.py``\n file in the instance folder if it exists. For example, when\n deploying, this can be used to set a real ``SECRET_KEY``.\n\n * ``test_config`` can also be passed to the factory, and will be\n used instead of the instance configuration. This is so the tests\n you'll write later in the tutorial can be configured\n independently of any development values you have configured.\n\n#. :func:`os.makedirs` ensures that\n :attr:`app.instance_path ` exists. Flask\n doesn't create the instance folder automatically, but it needs to be\n created because your project will create the SQLite database file\n there.\n\n#. :meth:`@app.route() ` creates a simple route so you can\n see the application working before getting into the rest of the\n tutorial. It creates a connection between the URL ``/hello`` and a\n function that returns a response, the string ``'Hello, World!'`` in\n this case.\n\n\nRun The Application\n-------------------\n\nNow you can run your application using the ``flask`` command. From the\nterminal, tell Flask where to find your application, then run it in\ndevelopment mode. Remember, you should still be in the top-level\n``flask-tutorial`` directory, not the ``flaskr`` package.\n\nDevelopment mode shows an interactive debugger whenever a page raises an\nexception, and restarts the server whenever you make changes to the\ncode. You can leave it running and just reload the browser page as you\nfollow the tutorial.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=flaskr\n $ export FLASK_ENV=development\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=flaskr\n > set FLASK_ENV=development\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"flaskr\"\n > $env:FLASK_ENV = \"development\"\n > flask run\n\nYou'll see output similar to this:\n\n.. code-block:: none\n\n * Serving Flask app \"flaskr\"\n * Environment: development\n * Debug mode: on\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n * Restarting with stat\n * Debugger is active!\n * Debugger PIN: 855-212-761\n\nVisit http://127.0.0.1:5000/hello in a browser and you should see the\n\"Hello, World!\" message. Congratulations, you're now running your Flask\nweb application!\n\nContinue to :doc:`database`.\n"},{"id":12,"name":"SECURITY.md","nodeType":"TextFile","path":".github","text":"# Security Policy\n\nIf you believe you have identified a security issue with a Pallets\nproject, **do not open a public issue**. To responsibly report a\nsecurity issue, please email security@palletsprojects.com. A security\nteam member will contact you acknowledging the report and how to\ncontinue.\n\nBe sure to include as much detail as necessary in your report. As with\nreporting normal issues, a minimal reproducible example will help the\nmaintainers address the issue faster. If you are able, you may also\ninclude a fix for the issue generated with `git format-patch`.\n\nThe current and previous release will receive security patches, with\nolder versions evaluated based on usage information and severity.\n\nAfter fixing an issue, we will make a security release along with an\nannouncement on our blog. We may obtain a CVE id as well. You may\ninclude a name and link if you would like to be credited for the report.\n"},{"fileName":"factory.py","filePath":"tests/test_apps/cliapp","id":13,"nodeType":"File","text":"from flask import Flask\n\n\ndef create_app():\n return Flask(\"app\")\n\n\ndef create_app2(foo, bar):\n return Flask(\"_\".join([\"app2\", foo, bar]))\n\n\ndef no_app():\n pass\n"},{"id":14,"name":"design.rst","nodeType":"TextFile","path":"docs","text":"Design Decisions in Flask\n=========================\n\nIf you are curious why Flask does certain things the way it does and not\ndifferently, this section is for you. This should give you an idea about\nsome of the design decisions that may appear arbitrary and surprising at\nfirst, especially in direct comparison with other frameworks.\n\n\nThe Explicit Application Object\n-------------------------------\n\nA Python web application based on WSGI has to have one central callable\nobject that implements the actual application. In Flask this is an\ninstance of the :class:`~flask.Flask` class. Each Flask application has\nto create an instance of this class itself and pass it the name of the\nmodule, but why can't Flask do that itself?\n\nWithout such an explicit application object the following code::\n\n from flask import Flask\n app = Flask(__name__)\n\n @app.route('/')\n def index():\n return 'Hello World!'\n\nWould look like this instead::\n\n from hypothetical_flask import route\n\n @route('/')\n def index():\n return 'Hello World!'\n\nThere are three major reasons for this. The most important one is that\nimplicit application objects require that there may only be one instance at\nthe time. There are ways to fake multiple applications with a single\napplication object, like maintaining a stack of applications, but this\ncauses some problems I won't outline here in detail. Now the question is:\nwhen does a microframework need more than one application at the same\ntime? A good example for this is unit testing. When you want to test\nsomething it can be very helpful to create a minimal application to test\nspecific behavior. When the application object is deleted everything it\nallocated will be freed again.\n\nAnother thing that becomes possible when you have an explicit object lying\naround in your code is that you can subclass the base class\n(:class:`~flask.Flask`) to alter specific behavior. This would not be\npossible without hacks if the object were created ahead of time for you\nbased on a class that is not exposed to you.\n\nBut there is another very important reason why Flask depends on an\nexplicit instantiation of that class: the package name. Whenever you\ncreate a Flask instance you usually pass it `__name__` as package name.\nFlask depends on that information to properly load resources relative\nto your module. With Python's outstanding support for reflection it can\nthen access the package to figure out where the templates and static files\nare stored (see :meth:`~flask.Flask.open_resource`). Now obviously there\nare frameworks around that do not need any configuration and will still be\nable to load templates relative to your application module. But they have\nto use the current working directory for that, which is a very unreliable\nway to determine where the application is. The current working directory\nis process-wide and if you are running multiple applications in one\nprocess (which could happen in a webserver without you knowing) the paths\nwill be off. Worse: many webservers do not set the working directory to\nthe directory of your application but to the document root which does not\nhave to be the same folder.\n\nThe third reason is \"explicit is better than implicit\". That object is\nyour WSGI application, you don't have to remember anything else. If you\nwant to apply a WSGI middleware, just wrap it and you're done (though\nthere are better ways to do that so that you do not lose the reference\nto the application object :meth:`~flask.Flask.wsgi_app`).\n\nFurthermore this design makes it possible to use a factory function to\ncreate the application which is very helpful for unit testing and similar\nthings (:doc:`/patterns/appfactories`).\n\nThe Routing System\n------------------\n\nFlask uses the Werkzeug routing system which was designed to\nautomatically order routes by complexity. This means that you can declare\nroutes in arbitrary order and they will still work as expected. This is a\nrequirement if you want to properly implement decorator based routing\nsince decorators could be fired in undefined order when the application is\nsplit into multiple modules.\n\nAnother design decision with the Werkzeug routing system is that routes\nin Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far\nwith that in that it will automatically redirect to a canonical URL if a route\nis ambiguous.\n\n\nOne Template Engine\n-------------------\n\nFlask decides on one template engine: Jinja2. Why doesn't Flask have a\npluggable template engine interface? You can obviously use a different\ntemplate engine, but Flask will still configure Jinja2 for you. While\nthat limitation that Jinja2 is *always* configured will probably go away,\nthe decision to bundle one template engine and use that will not.\n\nTemplate engines are like programming languages and each of those engines\nhas a certain understanding about how things work. On the surface they\nall work the same: you tell the engine to evaluate a template with a set\nof variables and take the return value as string.\n\nBut that's about where similarities end. Jinja2 for example has an\nextensive filter system, a certain way to do template inheritance,\nsupport for reusable blocks (macros) that can be used from inside\ntemplates and also from Python code, supports iterative template\nrendering, configurable syntax and more. On the other hand an engine\nlike Genshi is based on XML stream evaluation, template inheritance by\ntaking the availability of XPath into account and more. Mako on the\nother hand treats templates similar to Python modules.\n\nWhen it comes to connecting a template engine with an application or\nframework there is more than just rendering templates. For instance,\nFlask uses Jinja2's extensive autoescaping support. Also it provides\nways to access macros from Jinja2 templates.\n\nA template abstraction layer that would not take the unique features of\nthe template engines away is a science on its own and a too large\nundertaking for a microframework like Flask.\n\nFurthermore extensions can then easily depend on one template language\nbeing present. You can easily use your own templating language, but an\nextension could still depend on Jinja itself.\n\n\nMicro with Dependencies\n-----------------------\n\nWhy does Flask call itself a microframework and yet it depends on two\nlibraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look\nover to the Ruby side of web development there we have a protocol very\nsimilar to WSGI. Just that it's called Rack there, but besides that it\nlooks very much like a WSGI rendition for Ruby. But nearly all\napplications in Ruby land do not work with Rack directly, but on top of a\nlibrary with the same name. This Rack library has two equivalents in\nPython: WebOb (formerly Paste) and Werkzeug. Paste is still around but\nfrom my understanding it's sort of deprecated in favour of WebOb. The\ndevelopment of WebOb and Werkzeug started side by side with similar ideas\nin mind: be a good implementation of WSGI for other applications to take\nadvantage.\n\nFlask is a framework that takes advantage of the work already done by\nWerkzeug to properly interface WSGI (which can be a complex task at\ntimes). Thanks to recent developments in the Python package\ninfrastructure, packages with dependencies are no longer an issue and\nthere are very few reasons against having libraries that depend on others.\n\n\nThread Locals\n-------------\n\nFlask uses thread local objects (context local objects in fact, they\nsupport greenlet contexts as well) for request, session and an extra\nobject you can put your own things on (:data:`~flask.g`). Why is that and\nisn't that a bad idea?\n\nYes it is usually not such a bright idea to use thread locals. They cause\ntroubles for servers that are not based on the concept of threads and make\nlarge applications harder to maintain. However Flask is just not designed\nfor large applications or asynchronous servers. Flask wants to make it\nquick and easy to write a traditional web application.\n\nAlso see the :doc:`/becomingbig` section of the documentation for some\ninspiration for larger applications based on Flask.\n\n\nAsync/await and ASGI support\n----------------------------\n\nFlask supports ``async`` coroutines for view functions by executing the\ncoroutine on a separate thread instead of using an event loop on the\nmain thread as an async-first (ASGI) framework would. This is necessary\nfor Flask to remain backwards compatible with extensions and code built\nbefore ``async`` was introduced into Python. This compromise introduces\na performance cost compared with the ASGI frameworks, due to the\noverhead of the threads.\n\nDue to how tied to WSGI Flask's code is, it's not clear if it's possible\nto make the ``Flask`` class support ASGI and WSGI at the same time. Work\nis currently being done in Werkzeug to work with ASGI, which may\neventually enable support in Flask as well.\n\nSee :doc:`/async-await` for more discussion.\n\n\nWhat Flask is, What Flask is Not\n--------------------------------\n\nFlask will never have a database layer. It will not have a form library\nor anything else in that direction. Flask itself just bridges to Werkzeug\nto implement a proper WSGI application and to Jinja2 to handle templating.\nIt also binds to a few common standard library packages such as logging.\nEverything else is up for extensions.\n\nWhy is this the case? Because people have different preferences and\nrequirements and Flask could not meet those if it would force any of this\ninto the core. The majority of web applications will need a template\nengine in some sort. However not every application needs a SQL database.\n\nThe idea of Flask is to build a good foundation for all applications.\nEverything else is up to you or extensions.\n"},{"id":15,"name":"dev.in","nodeType":"TextFile","path":"requirements","text":"-r docs.in\n-r tests.in\n-r typing.in\npip-tools\npre-commit\ntox\n"},{"id":16,"name":"tests.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nTest Coverage\n=============\n\nWriting unit tests for your application lets you check that the code\nyou wrote works the way you expect. Flask provides a test client that\nsimulates requests to the application and returns the response data.\n\nYou should test as much of your code as possible. Code in functions only\nruns when the function is called, and code in branches, such as ``if``\nblocks, only runs when the condition is met. You want to make sure that\neach function is tested with data that covers each branch.\n\nThe closer you get to 100% coverage, the more comfortable you can be\nthat making a change won't unexpectedly change other behavior. However,\n100% coverage doesn't guarantee that your application doesn't have bugs.\nIn particular, it doesn't test how the user interacts with the\napplication in the browser. Despite this, test coverage is an important\ntool to use during development.\n\n.. note::\n This is being introduced late in the tutorial, but in your future\n projects you should test as you develop.\n\nYou'll use `pytest`_ and `coverage`_ to test and measure your code.\nInstall them both:\n\n.. code-block:: none\n\n $ pip install pytest coverage\n\n.. _pytest: https://pytest.readthedocs.io/\n.. _coverage: https://coverage.readthedocs.io/\n\n\nSetup and Fixtures\n------------------\n\nThe test code is located in the ``tests`` directory. This directory is\n*next to* the ``flaskr`` package, not inside it. The\n``tests/conftest.py`` file contains setup functions called *fixtures*\nthat each test will use. Tests are in Python modules that start with\n``test_``, and each test function in those modules also starts with\n``test_``.\n\nEach test will create a new temporary database file and populate some\ndata that will be used in the tests. Write a SQL file to insert that\ndata.\n\n.. code-block:: sql\n :caption: ``tests/data.sql``\n\n INSERT INTO user (username, password)\n VALUES\n ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),\n ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');\n\n INSERT INTO post (title, body, author_id, created)\n VALUES\n ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');\n\nThe ``app`` fixture will call the factory and pass ``test_config`` to\nconfigure the application and database for testing instead of using your\nlocal development configuration.\n\n.. code-block:: python\n :caption: ``tests/conftest.py``\n\n import os\n import tempfile\n\n import pytest\n from flaskr import create_app\n from flaskr.db import get_db, init_db\n\n with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:\n _data_sql = f.read().decode('utf8')\n\n\n @pytest.fixture\n def app():\n db_fd, db_path = tempfile.mkstemp()\n\n app = create_app({\n 'TESTING': True,\n 'DATABASE': db_path,\n })\n\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n os.close(db_fd)\n os.unlink(db_path)\n\n\n @pytest.fixture\n def client(app):\n return app.test_client()\n\n\n @pytest.fixture\n def runner(app):\n return app.test_cli_runner()\n\n:func:`tempfile.mkstemp` creates and opens a temporary file, returning\nthe file descriptor and the path to it. The ``DATABASE`` path is\noverridden so it points to this temporary path instead of the instance\nfolder. After setting the path, the database tables are created and the\ntest data is inserted. After the test is over, the temporary file is\nclosed and removed.\n\n:data:`TESTING` tells Flask that the app is in test mode. Flask changes\nsome internal behavior so it's easier to test, and other extensions can\nalso use the flag to make testing them easier.\n\nThe ``client`` fixture calls\n:meth:`app.test_client() ` with the application\nobject created by the ``app`` fixture. Tests will use the client to make\nrequests to the application without running the server.\n\nThe ``runner`` fixture is similar to ``client``.\n:meth:`app.test_cli_runner() ` creates a runner\nthat can call the Click commands registered with the application.\n\nPytest uses fixtures by matching their function names with the names\nof arguments in the test functions. For example, the ``test_hello``\nfunction you'll write next takes a ``client`` argument. Pytest matches\nthat with the ``client`` fixture function, calls it, and passes the\nreturned value to the test function.\n\n\nFactory\n-------\n\nThere's not much to test about the factory itself. Most of the code will\nbe executed for each test already, so if something fails the other tests\nwill notice.\n\nThe only behavior that can change is passing test config. If config is\nnot passed, there should be some default configuration, otherwise the\nconfiguration should be overridden.\n\n.. code-block:: python\n :caption: ``tests/test_factory.py``\n\n from flaskr import create_app\n\n\n def test_config():\n assert not create_app().testing\n assert create_app({'TESTING': True}).testing\n\n\n def test_hello(client):\n response = client.get('/hello')\n assert response.data == b'Hello, World!'\n\nYou added the ``hello`` route as an example when writing the factory at\nthe beginning of the tutorial. It returns \"Hello, World!\", so the test\nchecks that the response data matches.\n\n\nDatabase\n--------\n\nWithin an application context, ``get_db`` should return the same\nconnection each time it's called. After the context, the connection\nshould be closed.\n\n.. code-block:: python\n :caption: ``tests/test_db.py``\n\n import sqlite3\n\n import pytest\n from flaskr.db import get_db\n\n\n def test_get_close_db(app):\n with app.app_context():\n db = get_db()\n assert db is get_db()\n\n with pytest.raises(sqlite3.ProgrammingError) as e:\n db.execute('SELECT 1')\n\n assert 'closed' in str(e.value)\n\nThe ``init-db`` command should call the ``init_db`` function and output\na message.\n\n.. code-block:: python\n :caption: ``tests/test_db.py``\n\n def test_init_db_command(runner, monkeypatch):\n class Recorder(object):\n called = False\n\n def fake_init_db():\n Recorder.called = True\n\n monkeypatch.setattr('flaskr.db.init_db', fake_init_db)\n result = runner.invoke(args=['init-db'])\n assert 'Initialized' in result.output\n assert Recorder.called\n\nThis test uses Pytest's ``monkeypatch`` fixture to replace the\n``init_db`` function with one that records that it's been called. The\n``runner`` fixture you wrote above is used to call the ``init-db``\ncommand by name.\n\n\nAuthentication\n--------------\n\nFor most of the views, a user needs to be logged in. The easiest way to\ndo this in tests is to make a ``POST`` request to the ``login`` view\nwith the client. Rather than writing that out every time, you can write\na class with methods to do that, and use a fixture to pass it the client\nfor each test.\n\n.. code-block:: python\n :caption: ``tests/conftest.py``\n\n class AuthActions(object):\n def __init__(self, client):\n self._client = client\n\n def login(self, username='test', password='test'):\n return self._client.post(\n '/auth/login',\n data={'username': username, 'password': password}\n )\n\n def logout(self):\n return self._client.get('/auth/logout')\n\n\n @pytest.fixture\n def auth(client):\n return AuthActions(client)\n\nWith the ``auth`` fixture, you can call ``auth.login()`` in a test to\nlog in as the ``test`` user, which was inserted as part of the test\ndata in the ``app`` fixture.\n\nThe ``register`` view should render successfully on ``GET``. On ``POST``\nwith valid form data, it should redirect to the login URL and the user's\ndata should be in the database. Invalid data should display error\nmessages.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n import pytest\n from flask import g, session\n from flaskr.db import get_db\n\n\n def test_register(client, app):\n assert client.get('/auth/register').status_code == 200\n response = client.post(\n '/auth/register', data={'username': 'a', 'password': 'a'}\n )\n assert 'http://localhost/auth/login' == response.headers['Location']\n\n with app.app_context():\n assert get_db().execute(\n \"select * from user where username = 'a'\",\n ).fetchone() is not None\n\n\n @pytest.mark.parametrize(('username', 'password', 'message'), (\n ('', '', b'Username is required.'),\n ('a', '', b'Password is required.'),\n ('test', 'test', b'already registered'),\n ))\n def test_register_validate_input(client, username, password, message):\n response = client.post(\n '/auth/register',\n data={'username': username, 'password': password}\n )\n assert message in response.data\n\n:meth:`client.get() ` makes a ``GET`` request\nand returns the :class:`Response` object returned by Flask. Similarly,\n:meth:`client.post() ` makes a ``POST``\nrequest, converting the ``data`` dict into form data.\n\nTo test that the page renders successfully, a simple request is made and\nchecked for a ``200 OK`` :attr:`~Response.status_code`. If\nrendering failed, Flask would return a ``500 Internal Server Error``\ncode.\n\n:attr:`~Response.headers` will have a ``Location`` header with the login\nURL when the register view redirects to the login view.\n\n:attr:`~Response.data` contains the body of the response as bytes. If\nyou expect a certain value to render on the page, check that it's in\n``data``. Bytes must be compared to bytes. If you want to compare text,\nuse :meth:`get_data(as_text=True) `\ninstead.\n\n``pytest.mark.parametrize`` tells Pytest to run the same test function\nwith different arguments. You use it here to test different invalid\ninput and error messages without writing the same code three times.\n\nThe tests for the ``login`` view are very similar to those for\n``register``. Rather than testing the data in the database,\n:data:`session` should have ``user_id`` set after logging in.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n def test_login(client, auth):\n assert client.get('/auth/login').status_code == 200\n response = auth.login()\n assert response.headers['Location'] == 'http://localhost/'\n\n with client:\n client.get('/')\n assert session['user_id'] == 1\n assert g.user['username'] == 'test'\n\n\n @pytest.mark.parametrize(('username', 'password', 'message'), (\n ('a', 'test', b'Incorrect username.'),\n ('test', 'a', b'Incorrect password.'),\n ))\n def test_login_validate_input(auth, username, password, message):\n response = auth.login(username, password)\n assert message in response.data\n\nUsing ``client`` in a ``with`` block allows accessing context variables\nsuch as :data:`session` after the response is returned. Normally,\naccessing ``session`` outside of a request would raise an error.\n\nTesting ``logout`` is the opposite of ``login``. :data:`session` should\nnot contain ``user_id`` after logging out.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n def test_logout(client, auth):\n auth.login()\n\n with client:\n auth.logout()\n assert 'user_id' not in session\n\n\nBlog\n----\n\nAll the blog views use the ``auth`` fixture you wrote earlier. Call\n``auth.login()`` and subsequent requests from the client will be logged\nin as the ``test`` user.\n\nThe ``index`` view should display information about the post that was\nadded with the test data. When logged in as the author, there should be\na link to edit the post.\n\nYou can also test some more authentication behavior while testing the\n``index`` view. When not logged in, each page shows links to log in or\nregister. When logged in, there's a link to log out.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n import pytest\n from flaskr.db import get_db\n\n\n def test_index(client, auth):\n response = client.get('/')\n assert b\"Log In\" in response.data\n assert b\"Register\" in response.data\n\n auth.login()\n response = client.get('/')\n assert b'Log Out' in response.data\n assert b'test title' in response.data\n assert b'by test on 2018-01-01' in response.data\n assert b'test\\nbody' in response.data\n assert b'href=\"/1/update\"' in response.data\n\nA user must be logged in to access the ``create``, ``update``, and\n``delete`` views. The logged in user must be the author of the post to\naccess ``update`` and ``delete``, otherwise a ``403 Forbidden`` status\nis returned. If a ``post`` with the given ``id`` doesn't exist,\n``update`` and ``delete`` should return ``404 Not Found``.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n @pytest.mark.parametrize('path', (\n '/create',\n '/1/update',\n '/1/delete',\n ))\n def test_login_required(client, path):\n response = client.post(path)\n assert response.headers['Location'] == 'http://localhost/auth/login'\n\n\n def test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db = get_db()\n db.execute('UPDATE post SET author_id = 2 WHERE id = 1')\n db.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post('/1/update').status_code == 403\n assert client.post('/1/delete').status_code == 403\n # current user doesn't see edit link\n assert b'href=\"/1/update\"' not in client.get('/').data\n\n\n @pytest.mark.parametrize('path', (\n '/2/update',\n '/2/delete',\n ))\n def test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404\n\nThe ``create`` and ``update`` views should render and return a\n``200 OK`` status for a ``GET`` request. When valid data is sent in a\n``POST`` request, ``create`` should insert the new post data into the\ndatabase, and ``update`` should modify the existing data. Both pages\nshould show an error message on invalid data.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n def test_create(client, auth, app):\n auth.login()\n assert client.get('/create').status_code == 200\n client.post('/create', data={'title': 'created', 'body': ''})\n\n with app.app_context():\n db = get_db()\n count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]\n assert count == 2\n\n\n def test_update(client, auth, app):\n auth.login()\n assert client.get('/1/update').status_code == 200\n client.post('/1/update', data={'title': 'updated', 'body': ''})\n\n with app.app_context():\n db = get_db()\n post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()\n assert post['title'] == 'updated'\n\n\n @pytest.mark.parametrize('path', (\n '/create',\n '/1/update',\n ))\n def test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={'title': '', 'body': ''})\n assert b'Title is required.' in response.data\n\nThe ``delete`` view should redirect to the index URL and the post should\nno longer exist in the database.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n def test_delete(client, auth, app):\n auth.login()\n response = client.post('/1/delete')\n assert response.headers['Location'] == 'http://localhost/'\n\n with app.app_context():\n db = get_db()\n post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()\n assert post is None\n\n\nRunning the Tests\n-----------------\n\nSome extra configuration, which is not required but makes running\ntests with coverage less verbose, can be added to the project's\n``setup.cfg`` file.\n\n.. code-block:: none\n :caption: ``setup.cfg``\n\n [tool:pytest]\n testpaths = tests\n\n [coverage:run]\n branch = True\n source =\n flaskr\n\nTo run the tests, use the ``pytest`` command. It will find and run all\nthe test functions you've written.\n\n.. code-block:: none\n\n $ pytest\n\n ========================= test session starts ==========================\n platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0\n rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg\n collected 23 items\n\n tests/test_auth.py ........ [ 34%]\n tests/test_blog.py ............ [ 86%]\n tests/test_db.py .. [ 95%]\n tests/test_factory.py .. [100%]\n\n ====================== 24 passed in 0.64 seconds =======================\n\nIf any tests fail, pytest will show the error that was raised. You can\nrun ``pytest -v`` to get a list of each test function rather than dots.\n\nTo measure the code coverage of your tests, use the ``coverage`` command\nto run pytest instead of running it directly.\n\n.. code-block:: none\n\n $ coverage run -m pytest\n\nYou can either view a simple coverage report in the terminal:\n\n.. code-block:: none\n\n $ coverage report\n\n Name Stmts Miss Branch BrPart Cover\n ------------------------------------------------------\n flaskr/__init__.py 21 0 2 0 100%\n flaskr/auth.py 54 0 22 0 100%\n flaskr/blog.py 54 0 16 0 100%\n flaskr/db.py 24 0 4 0 100%\n ------------------------------------------------------\n TOTAL 153 0 44 0 100%\n\nAn HTML report allows you to see which lines were covered in each file:\n\n.. code-block:: none\n\n $ coverage html\n\nThis generates files in the ``htmlcov`` directory. Open\n``htmlcov/index.html`` in your browser to see the report.\n\nContinue to :doc:`deploy`.\n"},{"id":17,"name":"examples/tutorial/flaskr/static","nodeType":"Package"},{"id":18,"name":"style.css","nodeType":"TextFile","path":"examples/tutorial/flaskr/static","text":"html {\n font-family: sans-serif;\n background: #eee;\n padding: 1rem;\n}\n\nbody {\n max-width: 960px;\n margin: 0 auto;\n background: white;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: serif;\n color: #377ba8;\n margin: 1rem 0;\n}\n\na {\n color: #377ba8;\n}\n\nhr {\n border: none;\n border-top: 1px solid lightgray;\n}\n\nnav {\n background: lightgray;\n display: flex;\n align-items: center;\n padding: 0 0.5rem;\n}\n\nnav h1 {\n flex: auto;\n margin: 0;\n}\n\nnav h1 a {\n text-decoration: none;\n padding: 0.25rem 0.5rem;\n}\n\nnav ul {\n display: flex;\n list-style: none;\n margin: 0;\n padding: 0;\n}\n\nnav ul li a, nav ul li span, header .action {\n display: block;\n padding: 0.5rem;\n}\n\n.content {\n padding: 0 1rem 1rem;\n}\n\n.content > header {\n border-bottom: 1px solid lightgray;\n display: flex;\n align-items: flex-end;\n}\n\n.content > header h1 {\n flex: auto;\n margin: 1rem 0 0.25rem 0;\n}\n\n.flash {\n margin: 1em 0;\n padding: 1em;\n background: #cae6f6;\n border: 1px solid #377ba8;\n}\n\n.post > header {\n display: flex;\n align-items: flex-end;\n font-size: 0.85em;\n}\n\n.post > header > div:first-of-type {\n flex: auto;\n}\n\n.post > header h1 {\n font-size: 1.5em;\n margin-bottom: 0;\n}\n\n.post .about {\n color: slategray;\n font-style: italic;\n}\n\n.post .body {\n white-space: pre-line;\n}\n\n.content:last-child {\n margin-bottom: 0;\n}\n\n.content form {\n margin: 1em 0;\n display: flex;\n flex-direction: column;\n}\n\n.content label {\n font-weight: bold;\n margin-bottom: 0.5em;\n}\n\n.content input, .content textarea {\n margin-bottom: 1em;\n}\n\n.content textarea {\n min-height: 12em;\n resize: vertical;\n}\n\ninput.danger {\n color: #cc2f2e;\n}\n\ninput[type=submit] {\n align-self: start;\n min-width: 10em;\n}\n"},{"id":19,"name":"testing.rst","nodeType":"TextFile","path":"docs","text":"Testing Flask Applications\n==========================\n\n **Something that is untested is broken.**\n\nThe origin of this quote is unknown and while it is not entirely correct, it\nis also not far from the truth. Untested applications make it hard to\nimprove existing code and developers of untested applications tend to\nbecome pretty paranoid. If an application has automated tests, you can\nsafely make changes and instantly know if anything breaks.\n\nFlask provides a way to test your application by exposing the Werkzeug\ntest :class:`~werkzeug.test.Client` and handling the context locals for you.\nYou can then use that with your favourite testing solution.\n\nIn this documentation we will use the `pytest`_ package as the base\nframework for our tests. You can install it with ``pip``, like so::\n\n $ pip install pytest\n\n.. _pytest: https://docs.pytest.org/\n\nThe Application\n---------------\n\nFirst, we need an application to test; we will use the application from\nthe :doc:`tutorial/index`. If you don't have that application yet, get\nthe source code from :gh:`the examples `.\n\nSo that we can import the module ``flaskr`` correctly, we need to run\n``pip install -e .`` in the folder ``tutorial``.\n\nThe Testing Skeleton\n--------------------\n\nWe begin by adding a tests directory under the application root. Then\ncreate a Python file to store our tests (:file:`test_flaskr.py`). When we\nformat the filename like ``test_*.py``, it will be auto-discoverable by\npytest.\n\nNext, we create a `pytest fixture`_ called\n:func:`client` that configures\nthe application for testing and initializes a new database::\n\n import os\n import tempfile\n\n import pytest\n\n from flaskr import create_app\n\n\n @pytest.fixture\n def client():\n db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()\n flaskr.app.config['TESTING'] = True\n\n with flaskr.app.test_client() as client:\n with flaskr.app.app_context():\n flaskr.init_db()\n yield client\n\n os.close(db_fd)\n os.unlink(flaskr.app.config['DATABASE'])\n\nThis client fixture will be called by each individual test. It gives us a\nsimple interface to the application, where we can trigger test requests to the\napplication. The client will also keep track of cookies for us.\n\nDuring setup, the ``TESTING`` config flag is activated. What\nthis does is disable error catching during request handling, so that\nyou get better error reports when performing test requests against the\napplication.\n\nBecause SQLite3 is filesystem-based, we can easily use the\n:mod:`tempfile` module to create a temporary database and initialize it.\nThe :func:`~tempfile.mkstemp` function does two things for us: it returns a\nlow-level file handle and a random file name, the latter we use as\ndatabase name. We just have to keep the `db_fd` around so that we can use\nthe :func:`os.close` function to close the file.\n\nTo delete the database after the test, the fixture closes the file and removes\nit from the filesystem.\n\nIf we now run the test suite, we should see the following output::\n\n $ pytest\n\n ================ test session starts ================\n rootdir: ./flask/examples/flaskr, inifile: setup.cfg\n collected 0 items\n\n =========== no tests ran in 0.07 seconds ============\n\nEven though it did not run any actual tests, we already know that our\n``flaskr`` application is syntactically valid, otherwise the import\nwould have died with an exception.\n\n.. _pytest fixture:\n https://docs.pytest.org/en/latest/fixture.html\n\nThe First Test\n--------------\n\nNow it's time to start testing the functionality of the application.\nLet's check that the application shows \"No entries here so far\" if we\naccess the root of the application (``/``). To do this, we add a new\ntest function to :file:`test_flaskr.py`, like this::\n\n def test_empty_db(client):\n \"\"\"Start with a blank database.\"\"\"\n\n rv = client.get('/')\n assert b'No entries here so far' in rv.data\n\nNotice that our test functions begin with the word `test`; this allows\n`pytest`_ to automatically identify the function as a test to run.\n\nBy using ``client.get`` we can send an HTTP ``GET`` request to the\napplication with the given path. The return value will be a\n:class:`~flask.Flask.response_class` object. We can now use the\n:attr:`~werkzeug.wrappers.Response.data` attribute to inspect\nthe return value (as string) from the application.\nIn this case, we ensure that ``'No entries here so far'``\nis part of the output.\n\nRun it again and you should see one passing test::\n\n $ pytest -v\n\n ================ test session starts ================\n rootdir: ./flask/examples/flaskr, inifile: setup.cfg\n collected 1 items\n\n tests/test_flaskr.py::test_empty_db PASSED\n\n ============= 1 passed in 0.10 seconds ==============\n\nLogging In and Out\n------------------\n\nThe majority of the functionality of our application is only available for\nthe administrative user, so we need a way to log our test client in and out\nof the application. To do this, we fire some requests to the login and logout\npages with the required form data (username and password). And because the\nlogin and logout pages redirect, we tell the client to `follow_redirects`.\n\nAdd the following two functions to your :file:`test_flaskr.py` file::\n\n def login(client, username, password):\n return client.post('/login', data=dict(\n username=username,\n password=password\n ), follow_redirects=True)\n\n\n def logout(client):\n return client.get('/logout', follow_redirects=True)\n\nNow we can easily test that logging in and out works and that it fails with\ninvalid credentials. Add this new test function::\n\n def test_login_logout(client):\n \"\"\"Make sure login and logout works.\"\"\"\n\n username = flaskr.app.config[\"USERNAME\"]\n password = flaskr.app.config[\"PASSWORD\"]\n\n rv = login(client, username, password)\n assert b'You were logged in' in rv.data\n\n rv = logout(client)\n assert b'You were logged out' in rv.data\n\n rv = login(client, f\"{username}x\", password)\n assert b'Invalid username' in rv.data\n\n rv = login(client, username, f'{password}x')\n assert b'Invalid password' in rv.data\n\nTest Adding Messages\n--------------------\n\nWe should also test that adding messages works. Add a new test function\nlike this::\n\n def test_messages(client):\n \"\"\"Test that messages work.\"\"\"\n\n login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])\n rv = client.post('/add', data=dict(\n title='',\n text='HTML allowed here'\n ), follow_redirects=True)\n assert b'No entries here so far' not in rv.data\n assert b'<Hello>' in rv.data\n assert b'HTML allowed here' in rv.data\n\nHere we check that HTML is allowed in the text but not in the title,\nwhich is the intended behavior.\n\nRunning that should now give us three passing tests::\n\n $ pytest -v\n\n ================ test session starts ================\n rootdir: ./flask/examples/flaskr, inifile: setup.cfg\n collected 3 items\n\n tests/test_flaskr.py::test_empty_db PASSED\n tests/test_flaskr.py::test_login_logout PASSED\n tests/test_flaskr.py::test_messages PASSED\n\n ============= 3 passed in 0.23 seconds ==============\n\n\nOther Testing Tricks\n--------------------\n\nBesides using the test client as shown above, there is also the\n:meth:`~flask.Flask.test_request_context` method that can be used\nin combination with the ``with`` statement to activate a request context\ntemporarily. With this you can access the :class:`~flask.request`,\n:class:`~flask.g` and :class:`~flask.session` objects like in view\nfunctions. Here is a full example that demonstrates this approach::\n\n import flask\n\n app = flask.Flask(__name__)\n\n with app.test_request_context('/?name=Peter'):\n assert flask.request.path == '/'\n assert flask.request.args['name'] == 'Peter'\n\nAll the other objects that are context bound can be used in the same\nway.\n\nIf you want to test your application with different configurations and\nthere does not seem to be a good way to do that, consider switching to\napplication factories (see :doc:`patterns/appfactories`).\n\nNote however that if you are using a test request context, the\n:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`\nfunctions are not called automatically. However\n:meth:`~flask.Flask.teardown_request` functions are indeed executed when\nthe test request context leaves the ``with`` block. If you do want the\n:meth:`~flask.Flask.before_request` functions to be called as well, you\nneed to call :meth:`~flask.Flask.preprocess_request` yourself::\n\n app = flask.Flask(__name__)\n\n with app.test_request_context('/?name=Peter'):\n app.preprocess_request()\n ...\n\nThis can be necessary to open database connections or something similar\ndepending on how your application was designed.\n\nIf you want to call the :meth:`~flask.Flask.after_request` functions you\nneed to call into :meth:`~flask.Flask.process_response` which however\nrequires that you pass it a response object::\n\n app = flask.Flask(__name__)\n\n with app.test_request_context('/?name=Peter'):\n resp = Response('...')\n resp = app.process_response(resp)\n ...\n\nThis in general is less useful because at that point you can directly\nstart using the test client.\n\n.. _faking-resources:\n\nFaking Resources and Context\n----------------------------\n\n.. versionadded:: 0.10\n\nA very common pattern is to store user authorization information and\ndatabase connections on the application context or the :attr:`flask.g`\nobject. The general pattern for this is to put the object on there on\nfirst usage and then to remove it on a teardown. Imagine for instance\nthis code to get the current user::\n\n def get_user():\n user = getattr(g, 'user', None)\n if user is None:\n user = fetch_current_user_from_database()\n g.user = user\n return user\n\nFor a test it would be nice to override this user from the outside without\nhaving to change some code. This can be accomplished with\nhooking the :data:`flask.appcontext_pushed` signal::\n\n from contextlib import contextmanager\n from flask import appcontext_pushed, g\n\n @contextmanager\n def user_set(app, user):\n def handler(sender, **kwargs):\n g.user = user\n with appcontext_pushed.connected_to(handler, app):\n yield\n\nAnd then to use it::\n\n from flask import json, jsonify\n\n @app.route('/users/me')\n def users_me():\n return jsonify(username=g.user.username)\n\n with user_set(app, my_user):\n with app.test_client() as c:\n resp = c.get('/users/me')\n data = json.loads(resp.data)\n assert data['username'] == my_user.username\n\n\nKeeping the Context Around\n--------------------------\n\n.. versionadded:: 0.4\n\nSometimes it is helpful to trigger a regular request but still keep the\ncontext around for a little longer so that additional introspection can\nhappen. With Flask 0.4 this is possible by using the\n:meth:`~flask.Flask.test_client` with a ``with`` block::\n\n app = flask.Flask(__name__)\n\n with app.test_client() as c:\n rv = c.get('/?tequila=42')\n assert request.args['tequila'] == '42'\n\nIf you were to use just the :meth:`~flask.Flask.test_client` without\nthe ``with`` block, the ``assert`` would fail with an error because `request`\nis no longer available (because you are trying to use it\noutside of the actual request).\n\n\nAccessing and Modifying Sessions\n--------------------------------\n\n.. versionadded:: 0.8\n\nSometimes it can be very helpful to access or modify the sessions from the\ntest client. Generally there are two ways for this. If you just want to\nensure that a session has certain keys set to certain values you can just\nkeep the context around and access :data:`flask.session`::\n\n with app.test_client() as c:\n rv = c.get('/')\n assert flask.session['foo'] == 42\n\nThis however does not make it possible to also modify the session or to\naccess the session before a request was fired. Starting with Flask 0.8 we\nprovide a so called “session transaction” which simulates the appropriate\ncalls to open a session in the context of the test client and to modify\nit. At the end of the transaction the session is stored and ready to be\nused by the test client. This works independently of the session backend used::\n\n with app.test_client() as c:\n with c.session_transaction() as sess:\n sess['a_key'] = 'a value'\n\n # once this is reached the session was stored and ready to be used by the client\n c.get(...)\n\nNote that in this case you have to use the ``sess`` object instead of the\n:data:`flask.session` proxy. The object however itself will provide the\nsame interface.\n\n\nTesting JSON APIs\n-----------------\n\n.. versionadded:: 1.0\n\nFlask has great support for JSON, and is a popular choice for building JSON\nAPIs. Making requests with JSON data and examining JSON data in responses is\nvery convenient::\n\n from flask import request, jsonify\n\n @app.route('/api/auth')\n def auth():\n json_data = request.get_json()\n email = json_data['email']\n password = json_data['password']\n return jsonify(token=generate_token(email, password))\n\n with app.test_client() as c:\n rv = c.post('/api/auth', json={\n 'email': 'flask@example.com', 'password': 'secret'\n })\n json_data = rv.get_json()\n assert verify_token(email, json_data['token'])\n\nPassing the ``json`` argument in the test client methods sets the request data\nto the JSON-serialized object and sets the content type to\n``application/json``. You can get the JSON data from the request or response\nwith ``get_json``.\n\n\n.. _testing-cli:\n\nTesting CLI Commands\n--------------------\n\nClick comes with `utilities for testing`_ your CLI commands. A\n:class:`~click.testing.CliRunner` runs commands in isolation and\ncaptures the output in a :class:`~click.testing.Result` object.\n\nFlask provides :meth:`~flask.Flask.test_cli_runner` to create a\n:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the\nCLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`\nmethod to call commands in the same way they would be called from the\ncommand line. ::\n\n import click\n\n @app.cli.command('hello')\n @click.option('--name', default='World')\n def hello_command(name):\n click.echo(f'Hello, {name}!')\n\n def test_hello():\n runner = app.test_cli_runner()\n\n # invoke the command directly\n result = runner.invoke(hello_command, ['--name', 'Flask'])\n assert 'Hello, Flask' in result.output\n\n # or by name\n result = runner.invoke(args=['hello'])\n assert 'World' in result.output\n\nIn the example above, invoking the command by name is useful because it\nverifies that the command was correctly registered with the app.\n\nIf you want to test how your command parses parameters, without running\nthe command, use its :meth:`~click.BaseCommand.make_context` method.\nThis is useful for testing complex validation rules and custom types. ::\n\n def upper(ctx, param, value):\n if value is not None:\n return value.upper()\n\n @app.cli.command('hello')\n @click.option('--name', default='World', callback=upper)\n def hello_command(name):\n click.echo(f'Hello, {name}!')\n\n def test_hello_params():\n context = hello_command.make_context('hello', ['--name', 'flask'])\n assert context.params['name'] == 'FLASK'\n\n.. _click: https://click.palletsprojects.com/\n.. _utilities for testing: https://click.palletsprojects.com/testing/\n"},{"id":20,"name":"deploy.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Deploy to Production\n====================\n\nThis part of the tutorial assumes you have a server that you want to\ndeploy your application to. It gives an overview of how to create the\ndistribution file and install it, but won't go into specifics about\nwhat server or software to use. You can set up a new environment on your\ndevelopment computer to try out the instructions below, but probably\nshouldn't use it for hosting a real public application. See\n:doc:`/deploying/index` for a list of many different ways to host your\napplication.\n\n\nBuild and Install\n-----------------\n\nWhen you want to deploy your application elsewhere, you build a\ndistribution file. The current standard for Python distribution is the\n*wheel* format, with the ``.whl`` extension. Make sure the wheel library\nis installed first:\n\n.. code-block:: none\n\n $ pip install wheel\n\nRunning ``setup.py`` with Python gives you a command line tool to issue\nbuild-related commands. The ``bdist_wheel`` command will build a wheel\ndistribution file.\n\n.. code-block:: none\n\n $ python setup.py bdist_wheel\n\nYou can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The\nfile name is in the format of {project name}-{version}-{python tag}\n-{abi tag}-{platform tag}.\n\nCopy this file to another machine,\n:ref:`set up a new virtualenv `, then install the\nfile with ``pip``.\n\n.. code-block:: none\n\n $ pip install flaskr-1.0.0-py3-none-any.whl\n\nPip will install your project along with its dependencies.\n\nSince this is a different machine, you need to run ``init-db`` again to\ncreate the database in the instance folder.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=flaskr\n $ flask init-db\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=flaskr\n > flask init-db\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"flaskr\"\n > flask init-db\n\nWhen Flask detects that it's installed (not in editable mode), it uses\na different directory for the instance folder. You can find it at\n``venv/var/flaskr-instance`` instead.\n\n\nConfigure the Secret Key\n------------------------\n\nIn the beginning of the tutorial that you gave a default value for\n:data:`SECRET_KEY`. This should be changed to some random bytes in\nproduction. Otherwise, attackers could use the public ``'dev'`` key to\nmodify the session cookie, or anything else that uses the secret key.\n\nYou can use the following command to output a random secret key:\n\n.. code-block:: none\n\n $ python -c 'import os; print(os.urandom(16))'\n\n b'_5#y2L\"F4Q8z\\n\\xec]/'\n\nCreate the ``config.py`` file in the instance folder, which the factory\nwill read from if it exists. Copy the generated value into it.\n\n.. code-block:: python\n :caption: ``venv/var/flaskr-instance/config.py``\n\n SECRET_KEY = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\nYou can also set any other necessary configuration here, although\n``SECRET_KEY`` is the only one needed for Flaskr.\n\n\nRun with a Production Server\n----------------------------\n\nWhen running publicly rather than in development, you should not use the\nbuilt-in development server (``flask run``). The development server is\nprovided by Werkzeug for convenience, but is not designed to be\nparticularly efficient, stable, or secure.\n\nInstead, use a production WSGI server. For example, to use `Waitress`_,\nfirst install it in the virtual environment:\n\n.. code-block:: none\n\n $ pip install waitress\n\nYou need to tell Waitress about your application, but it doesn't use\n``FLASK_APP`` like ``flask run`` does. You need to tell it to import and\ncall the application factory to get an application object.\n\n.. code-block:: none\n\n $ waitress-serve --call 'flaskr:create_app'\n\n Serving on http://0.0.0.0:8080\n\nSee :doc:`/deploying/index` for a list of many different ways to host\nyour application. Waitress is just an example, chosen for the tutorial\nbecause it supports both Windows and Linux. There are many more WSGI\nservers and deployment options that you may choose for your project.\n\n.. _Waitress: https://docs.pylonsproject.org/projects/waitress/en/stable/\n\nContinue to :doc:`next`.\n"},{"id":21,"name":"templates.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nTemplates\n=========\n\nYou've written the authentication views for your application, but if\nyou're running the server and try to go to any of the URLs, you'll see a\n``TemplateNotFound`` error. That's because the views are calling\n:func:`render_template`, but you haven't written the templates yet.\nThe template files will be stored in the ``templates`` directory inside\nthe ``flaskr`` package.\n\nTemplates are files that contain static data as well as placeholders\nfor dynamic data. A template is rendered with specific data to produce a\nfinal document. Flask uses the `Jinja`_ template library to render\ntemplates.\n\nIn your application, you will use templates to render `HTML`_ which\nwill display in the user's browser. In Flask, Jinja is configured to\n*autoescape* any data that is rendered in HTML templates. This means\nthat it's safe to render user input; any characters they've entered that\ncould mess with the HTML, such as ``<`` and ``>`` will be *escaped* with\n*safe* values that look the same in the browser but don't cause unwanted\neffects.\n\nJinja looks and behaves mostly like Python. Special delimiters are used\nto distinguish Jinja syntax from the static data in the template.\nAnything between ``{{`` and ``}}`` is an expression that will be output\nto the final document. ``{%`` and ``%}`` denotes a control flow\nstatement like ``if`` and ``for``. Unlike Python, blocks are denoted\nby start and end tags rather than indentation since static text within\na block could change indentation.\n\n.. _Jinja: https://jinja.palletsprojects.com/templates/\n.. _HTML: https://developer.mozilla.org/docs/Web/HTML\n\n\nThe Base Layout\n---------------\n\nEach page in the application will have the same basic layout around a\ndifferent body. Instead of writing the entire HTML structure in each\ntemplate, each template will *extend* a base template and override\nspecific sections.\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/base.html``\n\n \n {% block title %}{% endblock %} - Flaskr\n \n \n
\n
\n {% block header %}{% endblock %}\n
\n {% for message in get_flashed_messages() %}\n
{{ message }}
\n {% endfor %}\n {% block content %}{% endblock %}\n
\n\n:data:`g` is automatically available in templates. Based on if\n``g.user`` is set (from ``load_logged_in_user``), either the username\nand a log out link are displayed, or links to register and log in\nare displayed. :func:`url_for` is also automatically available, and is\nused to generate URLs to views instead of writing them out manually.\n\nAfter the page title, and before the content, the template loops over\neach message returned by :func:`get_flashed_messages`. You used\n:func:`flash` in the views to show error messages, and this is the code\nthat will display them.\n\nThere are three blocks defined here that will be overridden in the other\ntemplates:\n\n#. ``{% block title %}`` will change the title displayed in the\n browser's tab and window title.\n\n#. ``{% block header %}`` is similar to ``title`` but will change the\n title displayed on the page.\n\n#. ``{% block content %}`` is where the content of each page goes, such\n as the login form or a blog post.\n\nThe base template is directly in the ``templates`` directory. To keep\nthe others organized, the templates for a blueprint will be placed in a\ndirectory with the same name as the blueprint.\n\n\nRegister\n--------\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/auth/register.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Register{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n {% endblock %}\n\n``{% extends 'base.html' %}`` tells Jinja that this template should\nreplace the blocks from the base template. All the rendered content must\nappear inside ``{% block %}`` tags that override blocks from the base\ntemplate.\n\nA useful pattern used here is to place ``{% block title %}`` inside\n``{% block header %}``. This will set the title block and then output\nthe value of it into the header block, so that both the window and page\nshare the same title without writing it twice.\n\nThe ``input`` tags are using the ``required`` attribute here. This tells\nthe browser not to submit the form until those fields are filled in. If\nthe user is using an older browser that doesn't support that attribute,\nor if they are using something besides a browser to make requests, you\nstill want to validate the data in the Flask view. It's important to\nalways fully validate the data on the server, even if the client does\nsome validation as well.\n\n\nLog In\n------\n\nThis is identical to the register template except for the title and\nsubmit button.\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/auth/login.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Log In{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n {% endblock %}\n\n\nRegister A User\n---------------\n\nNow that the authentication templates are written, you can register a\nuser. Make sure the server is still running (``flask run`` if it's not),\nthen go to http://127.0.0.1:5000/auth/register.\n\nTry clicking the \"Register\" button without filling out the form and see\nthat the browser shows an error message. Try removing the ``required``\nattributes from the ``register.html`` template and click \"Register\"\nagain. Instead of the browser showing an error, the page will reload and\nthe error from :func:`flash` in the view will be shown.\n\nFill out a username and password and you'll be redirected to the login\npage. Try entering an incorrect username, or the correct username and\nincorrect password. If you log in you'll get an error because there's\nno ``index`` view to redirect to yet.\n\nContinue to :doc:`static`.\n"},{"id":22,"name":"typing.txt","nodeType":"TextFile","path":"requirements","text":"#\n# This file is autogenerated by pip-compile\n# To update, run:\n#\n# pip-compile requirements/typing.in\n#\nmypy-extensions==0.4.3\n # via mypy\nmypy==0.812\n # via -r requirements/typing.in\ntyped-ast==1.4.3\n # via mypy\ntyping-extensions==3.10.0.0\n # via mypy\n"},{"fileName":"multiapp.py","filePath":"tests/test_apps/cliapp","id":23,"nodeType":"File","text":"from flask import Flask\n\napp1 = Flask(\"app1\")\napp2 = Flask(\"app2\")\n"},{"id":24,"name":"tests.txt","nodeType":"TextFile","path":"requirements","text":"#\n# This file is autogenerated by pip-compile\n# To update, run:\n#\n# pip-compile requirements/tests.in\n#\nasgiref==3.3.4\n # via -r requirements/tests.in\nattrs==21.2.0\n # via pytest\nblinker==1.4\n # via -r requirements/tests.in\ngreenlet==1.1.0\n # via -r requirements/tests.in\niniconfig==1.1.1\n # via pytest\npackaging==20.9\n # via pytest\npluggy==0.13.1\n # via pytest\npy==1.10.0\n # via pytest\npyparsing==2.4.7\n # via packaging\npytest==6.2.4\n # via -r requirements/tests.in\npython-dotenv==0.17.1\n # via -r requirements/tests.in\ntoml==0.10.2\n # via pytest\n"},{"id":25,"name":"docs/patterns","nodeType":"Package"},{"id":26,"name":"appdispatch.rst","nodeType":"TextFile","path":"docs/patterns","text":"Application Dispatching\n=======================\n\nApplication dispatching is the process of combining multiple Flask\napplications on the WSGI level. You can combine not only Flask\napplications but any WSGI application. This would allow you to run a\nDjango and a Flask application in the same interpreter side by side if\nyou want. The usefulness of this depends on how the applications work\ninternally.\n\nThe fundamental difference from :doc:`packages` is that in this case you\nare running the same or different Flask applications that are entirely\nisolated from each other. They run different configurations and are\ndispatched on the WSGI level.\n\n\nWorking with this Document\n--------------------------\n\nEach of the techniques and examples below results in an ``application``\nobject that can be run with any WSGI server. For production, see\n:doc:`/deploying/index`. For development, Werkzeug provides a server\nthrough :func:`werkzeug.serving.run_simple`::\n\n from werkzeug.serving import run_simple\n run_simple('localhost', 5000, application, use_reloader=True)\n\nNote that :func:`run_simple ` is not intended for\nuse in production. Use a production WSGI server. See :doc:`/deploying/index`.\n\nIn order to use the interactive debugger, debugging must be enabled both on\nthe application and the simple server. Here is the \"hello world\" example with\ndebugging and :func:`run_simple `::\n\n from flask import Flask\n from werkzeug.serving import run_simple\n\n app = Flask(__name__)\n app.debug = True\n\n @app.route('/')\n def hello_world():\n return 'Hello World!'\n\n if __name__ == '__main__':\n run_simple('localhost', 5000, app,\n use_reloader=True, use_debugger=True, use_evalex=True)\n\n\nCombining Applications\n----------------------\n\nIf you have entirely separated applications and you want them to work next\nto each other in the same Python interpreter process you can take\nadvantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea\nhere is that each Flask application is a valid WSGI application and they\nare combined by the dispatcher middleware into a larger one that is\ndispatched based on prefix.\n\nFor example you could have your main application run on ``/`` and your\nbackend interface on ``/backend``::\n\n from werkzeug.middleware.dispatcher import DispatcherMiddleware\n from frontend_app import application as frontend\n from backend_app import application as backend\n\n application = DispatcherMiddleware(frontend, {\n '/backend': backend\n })\n\n\nDispatch by Subdomain\n---------------------\n\nSometimes you might want to use multiple instances of the same application\nwith different configurations. Assuming the application is created inside\na function and you can call that function to instantiate it, that is\nreally easy to implement. In order to develop your application to support\ncreating new instances in functions have a look at the\n:doc:`appfactories` pattern.\n\nA very common example would be creating applications per subdomain. For\ninstance you configure your webserver to dispatch all requests for all\nsubdomains to your application and you then use the subdomain information\nto create user-specific instances. Once you have your server set up to\nlisten on all subdomains you can use a very simple WSGI application to do\nthe dynamic application creation.\n\nThe perfect level for abstraction in that regard is the WSGI layer. You\nwrite your own WSGI application that looks at the request that comes and\ndelegates it to your Flask application. If that application does not\nexist yet, it is dynamically created and remembered::\n\n from threading import Lock\n\n class SubdomainDispatcher(object):\n\n def __init__(self, domain, create_app):\n self.domain = domain\n self.create_app = create_app\n self.lock = Lock()\n self.instances = {}\n\n def get_application(self, host):\n host = host.split(':')[0]\n assert host.endswith(self.domain), 'Configuration error'\n subdomain = host[:-len(self.domain)].rstrip('.')\n with self.lock:\n app = self.instances.get(subdomain)\n if app is None:\n app = self.create_app(subdomain)\n self.instances[subdomain] = app\n return app\n\n def __call__(self, environ, start_response):\n app = self.get_application(environ['HTTP_HOST'])\n return app(environ, start_response)\n\n\nThis dispatcher can then be used like this::\n\n from myapplication import create_app, get_user_for_subdomain\n from werkzeug.exceptions import NotFound\n\n def make_app(subdomain):\n user = get_user_for_subdomain(subdomain)\n if user is None:\n # if there is no user for that subdomain we still have\n # to return a WSGI application that handles that request.\n # We can then just return the NotFound() exception as\n # application which will render a default 404 page.\n # You might also redirect the user to the main page then\n return NotFound()\n\n # otherwise create the application for the specific user\n return create_app(user)\n\n application = SubdomainDispatcher('example.com', make_app)\n\n\nDispatch by Path\n----------------\n\nDispatching by a path on the URL is very similar. Instead of looking at\nthe ``Host`` header to figure out the subdomain one simply looks at the\nrequest path up to the first slash::\n\n from threading import Lock\n from werkzeug.wsgi import pop_path_info, peek_path_info\n\n class PathDispatcher(object):\n\n def __init__(self, default_app, create_app):\n self.default_app = default_app\n self.create_app = create_app\n self.lock = Lock()\n self.instances = {}\n\n def get_application(self, prefix):\n with self.lock:\n app = self.instances.get(prefix)\n if app is None:\n app = self.create_app(prefix)\n if app is not None:\n self.instances[prefix] = app\n return app\n\n def __call__(self, environ, start_response):\n app = self.get_application(peek_path_info(environ))\n if app is not None:\n pop_path_info(environ)\n else:\n app = self.default_app\n return app(environ, start_response)\n\nThe big difference between this and the subdomain one is that this one\nfalls back to another application if the creator function returns ``None``::\n\n from myapplication import create_app, default_app, get_user_for_prefix\n\n def make_app(prefix):\n user = get_user_for_prefix(prefix)\n if user is not None:\n return create_app(user)\n\n application = PathDispatcher(default_app, make_app)\n"},{"id":27,"name":"","nodeType":"Package"},{"id":28,"name":".pre-commit-config.yaml","nodeType":"TextFile","path":"","text":"ci:\n autoupdate_schedule: monthly\nrepos:\n - repo: https://github.com/asottile/pyupgrade\n rev: v2.15.0\n hooks:\n - id: pyupgrade\n args: [\"--py36-plus\"]\n - repo: https://github.com/asottile/reorder_python_imports\n rev: v2.5.0\n hooks:\n - id: reorder-python-imports\n name: Reorder Python imports (src, tests)\n files: \"^(?!examples/)\"\n args: [\"--application-directories\", \"src\"]\n - repo: https://github.com/psf/black\n rev: 21.5b1\n hooks:\n - id: black\n - repo: https://github.com/PyCQA/flake8\n rev: 3.9.2\n hooks:\n - id: flake8\n additional_dependencies:\n - flake8-bugbear\n - flake8-implicit-str-concat\n - repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v3.4.0\n hooks:\n - id: fix-byte-order-marker\n - id: trailing-whitespace\n - id: end-of-file-fixer\n"},{"id":29,"name":".editorconfig","nodeType":"TextFile","path":"","text":"root = true\n\n[*]\nindent_style = space\nindent_size = 4\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nend_of_line = lf\ncharset = utf-8\nmax_line_length = 88\n\n[*.{yml,yaml,json,js,css,html}]\nindent_size = 2\n"},{"id":30,"name":".readthedocs.yaml","nodeType":"TextFile","path":"","text":"version: 2\npython:\n install:\n - requirements: requirements/docs.txt\n - method: pip\n path: .\nsphinx:\n builder: dirhtml\n fail_on_warning: true\n"},{"fileName":"__init__.py","filePath":"tests/test_apps/cliapp","id":31,"nodeType":"File","text":""},{"id":32,"name":".gitignore","nodeType":"TextFile","path":"","text":".DS_Store\n.env\n.flaskenv\n*.pyc\n*.pyo\nenv/\nenv*\ndist/\nbuild/\n*.egg\n*.egg-info/\n_mailinglist\n.tox/\n.cache/\n.pytest_cache/\n.idea/\ndocs/_build/\n.vscode\n\n# Coverage reports\nhtmlcov/\n.coverage\n.coverage.*\n*,cover\n"},{"fileName":"app.py","filePath":"tests/test_apps/cliapp","id":33,"nodeType":"File","text":"from flask import Flask\n\ntestapp = Flask(\"testapp\")\n"},{"fileName":"importerrorapp.py","filePath":"tests/test_apps/cliapp","id":34,"nodeType":"File","text":"from flask import Flask\n\nraise ImportError()\n\ntestapp = Flask(\"testapp\")\n"},{"id":35,"name":"message.txt","nodeType":"TextFile","path":"tests/test_apps/cliapp","text":"So long, and thanks for all the fish.\n"},{"id":36,"name":"typing.in","nodeType":"TextFile","path":"requirements","text":"mypy\n"},{"id":37,"name":"examples/tutorial/flaskr","nodeType":"Package"},{"fileName":"__init__.py","filePath":"examples/tutorial/flaskr","id":38,"nodeType":"File","text":"import os\n\nfrom flask import Flask\n\n\ndef create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.route(\"/hello\")\n def hello():\n return \"Hello, World!\"\n\n # register the database commands\n from flaskr import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from flaskr import auth, blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.route, while giving the blog blueprint a url_prefix, but for\n # the tutorial the blog will be the main index\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n return app\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":39,"name":"testapp","nodeType":"Attribute","startLoc":3,"text":"testapp"},{"col":0,"comment":"null","endLoc":5,"header":"def create_app()","id":40,"name":"create_app","nodeType":"Function","startLoc":4,"text":"def create_app():\n return Flask(\"app\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":5,"id":41,"name":"testapp","nodeType":"Attribute","startLoc":5,"text":"testapp"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":42,"name":"app1","nodeType":"Attribute","startLoc":3,"text":"app1"},{"col":0,"comment":"Create and configure an instance of the Flask application.","endLoc":50,"header":"def create_app(test_config=None)","id":43,"name":"create_app","nodeType":"Function","startLoc":6,"text":"def create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.route(\"/hello\")\n def hello():\n return \"Hello, World!\"\n\n # register the database commands\n from flaskr import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from flaskr import auth, blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.route, while giving the blog blueprint a url_prefix, but for\n # the tutorial the blog will be the main index\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n return app"},{"id":44,"name":"distribute.rst","nodeType":"TextFile","path":"docs/patterns","text":"Deploying with Setuptools\n=========================\n\n`Setuptools`_, is an extension library that is commonly used to\ndistribute Python libraries and extensions. It extends distutils, a basic\nmodule installation system shipped with Python to also support various more\ncomplex constructs that make larger applications easier to distribute:\n\n- **support for dependencies**: a library or application can declare a\n list of other libraries it depends on which will be installed\n automatically for you.\n- **package registry**: setuptools registers your package with your\n Python installation. This makes it possible to query information\n provided by one package from another package. The best known feature of\n this system is the entry point support which allows one package to\n declare an \"entry point\" that another package can hook into to extend the\n other package.\n- **installation manager**: :command:`pip` can install other libraries for you.\n\nFlask itself, and all the libraries you can find on PyPI are distributed with\neither setuptools or distutils.\n\nIn this case we assume your application is called\n:file:`yourapplication.py` and you are not using a module, but a\npackage. If you have not yet converted your application into a package,\nhead over to :doc:`packages` to see how this can be done.\n\nA working deployment with setuptools is the first step into more complex\nand more automated deployment scenarios. If you want to fully automate\nthe process, also read the :doc:`fabric` chapter.\n\nBasic Setup Script\n------------------\n\nBecause you have Flask installed, you have setuptools available on your system.\nFlask already depends upon setuptools.\n\nStandard disclaimer applies: :ref:`use a virtualenv\n`.\n\nYour setup code always goes into a file named :file:`setup.py` next to your\napplication. The name of the file is only convention, but because\neverybody will look for a file with that name, you better not change it.\n\nA basic :file:`setup.py` file for a Flask application looks like this::\n\n from setuptools import setup\n\n setup(\n name='Your Application',\n version='1.0',\n long_description=__doc__,\n packages=['yourapplication'],\n include_package_data=True,\n zip_safe=False,\n install_requires=['Flask']\n )\n\nPlease keep in mind that you have to list subpackages explicitly. If you\nwant setuptools to lookup the packages for you automatically, you can use\nthe ``find_packages`` function::\n\n from setuptools import setup, find_packages\n\n setup(\n ...\n packages=find_packages()\n )\n\nMost parameters to the ``setup`` function should be self explanatory,\n``include_package_data`` and ``zip_safe`` might not be.\n``include_package_data`` tells setuptools to look for a :file:`MANIFEST.in` file\nand install all the entries that match as package data. We will use this\nto distribute the static files and templates along with the Python module\n(see :ref:`distributing-resources`). The ``zip_safe`` flag can be used to\nforce or prevent zip Archive creation. In general you probably don't want\nyour packages to be installed as zip files because some tools do not\nsupport them and they make debugging a lot harder.\n\n\nTagging Builds\n--------------\n\nIt is useful to distinguish between release and development builds. Add a\n:file:`setup.cfg` file to configure these options. ::\n\n [egg_info]\n tag_build = .dev\n tag_date = 1\n\n [aliases]\n release = egg_info -Db ''\n\nRunning ``python setup.py sdist`` will create a development package\nwith \".dev\" and the current date appended: ``flaskr-1.0.dev20160314.tar.gz``.\nRunning ``python setup.py release sdist`` will create a release package\nwith only the version: ``flaskr-1.0.tar.gz``.\n\n\n.. _distributing-resources:\n\nDistributing Resources\n----------------------\n\nIf you try to install the package you just created, you will notice that\nfolders like :file:`static` or :file:`templates` are not installed for you. The\nreason for this is that setuptools does not know which files to add for\nyou. What you should do, is to create a :file:`MANIFEST.in` file next to your\n:file:`setup.py` file. This file lists all the files that should be added to\nyour tarball::\n\n recursive-include yourapplication/templates *\n recursive-include yourapplication/static *\n\nDon't forget that even if you enlist them in your :file:`MANIFEST.in` file, they\nwon't be installed for you unless you set the `include_package_data`\nparameter of the ``setup`` function to ``True``!\n\n\nDeclaring Dependencies\n----------------------\n\nDependencies are declared in the ``install_requires`` parameter as a list.\nEach item in that list is the name of a package that should be pulled from\nPyPI on installation. By default it will always use the most recent\nversion, but you can also provide minimum and maximum version\nrequirements. Here some examples::\n\n install_requires=[\n 'Flask>=0.2',\n 'SQLAlchemy>=0.6',\n 'BrokenPackage>=0.7,<=1.0'\n ]\n\nAs mentioned earlier, dependencies are pulled from PyPI. What if you\nwant to depend on a package that cannot be found on PyPI and won't be\nbecause it is an internal package you don't want to share with anyone?\nJust do it as if there was a PyPI entry and provide a list of\nalternative locations where setuptools should look for tarballs::\n\n dependency_links=['http://example.com/yourfiles']\n\nMake sure that page has a directory listing and the links on the page are\npointing to the actual tarballs with their correct filenames as this is\nhow setuptools will find the files. If you have an internal company\nserver that contains the packages, provide the URL to that server.\n\n\nInstalling / Developing\n-----------------------\n\nTo install your application (ideally into a virtualenv) just run the\n:file:`setup.py` script with the ``install`` parameter. It will install your\napplication into the virtualenv's site-packages folder and also download\nand install all dependencies::\n\n $ python setup.py install\n\nIf you are developing on the package and also want the requirements to be\ninstalled, you can use the ``develop`` command instead::\n\n $ python setup.py develop\n\nThis has the advantage of just installing a link to the site-packages\nfolder instead of copying the data over. You can then continue to work on\nthe code without having to run ``install`` again after each change.\n\n\n.. _pip: https://pypi.org/project/pip/\n.. _Setuptools: https://pypi.org/project/setuptools/\n"},{"id":45,"name":".github/ISSUE_TEMPLATE","nodeType":"Package"},{"id":46,"name":"config.yml","nodeType":"TextFile","path":".github/ISSUE_TEMPLATE","text":"blank_issues_enabled: false\ncontact_links:\n - name: Security issue\n url: security@palletsprojects.com\n about: Do not report security issues publicly. Email our security contact.\n - name: Questions\n url: https://stackoverflow.com/questions/tagged/flask?tab=Frequent\n about: Search for and ask questions about your code on Stack Overflow.\n - name: Questions and discussions\n url: https://discord.gg/pallets\n about: Discuss questions about your code on our Discord chat.\n"},{"id":47,"name":"examples/tutorial/flaskr/templates/auth","nodeType":"Package"},{"id":48,"name":"login.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/auth","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Log In{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n{% endblock %}\n"},{"fileName":"auth.py","filePath":"examples/tutorial/flaskr","id":49,"nodeType":"File","text":"import functools\n\nfrom flask import Blueprint\nfrom flask import flash\nfrom flask import g\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import session\nfrom flask import url_for\nfrom werkzeug.security import check_password_hash\nfrom werkzeug.security import generate_password_hash\n\nfrom flaskr.db import get_db\n\nbp = Blueprint(\"auth\", __name__, url_prefix=\"/auth\")\n\n\ndef login_required(view):\n \"\"\"View decorator that redirects anonymous users to the login page.\"\"\"\n\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)\n\n return wrapped_view\n\n\n@bp.before_app_request\ndef load_logged_in_user():\n \"\"\"If a user id is stored in the session, load the user object from\n the database into ``g.user``.\"\"\"\n user_id = session.get(\"user_id\")\n\n if user_id is None:\n g.user = None\n else:\n g.user = (\n get_db().execute(\"SELECT * FROM user WHERE id = ?\", (user_id,)).fetchone()\n )\n\n\n@bp.route(\"/register\", methods=(\"GET\", \"POST\"))\ndef register():\n \"\"\"Register a new user.\n\n Validates that the username is not already taken. Hashes the\n password for security.\n \"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n\n if not username:\n error = \"Username is required.\"\n elif not password:\n error = \"Password is required.\"\n elif (\n db.execute(\"SELECT id FROM user WHERE username = ?\", (username,)).fetchone()\n is not None\n ):\n error = f\"User {username} is already registered.\"\n\n if error is None:\n # the name is available, store it in the database and go to\n # the login page\n db.execute(\n \"INSERT INTO user (username, password) VALUES (?, ?)\",\n (username, generate_password_hash(password)),\n )\n db.commit()\n return redirect(url_for(\"auth.login\"))\n\n flash(error)\n\n return render_template(\"auth/register.html\")\n\n\n@bp.route(\"/login\", methods=(\"GET\", \"POST\"))\ndef login():\n \"\"\"Log in a registered user by adding the user id to the session.\"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n user = db.execute(\n \"SELECT * FROM user WHERE username = ?\", (username,)\n ).fetchone()\n\n if user is None:\n error = \"Incorrect username.\"\n elif not check_password_hash(user[\"password\"], password):\n error = \"Incorrect password.\"\n\n if error is None:\n # store the user id in a new session and return to the index\n session.clear()\n session[\"user_id\"] = user[\"id\"]\n return redirect(url_for(\"index\"))\n\n flash(error)\n\n return render_template(\"auth/login.html\")\n\n\n@bp.route(\"/logout\")\ndef logout():\n \"\"\"Clear the current session, including the stored user id.\"\"\"\n session.clear()\n return redirect(url_for(\"index\"))\n"},{"col":0,"comment":"View decorator that redirects anonymous users to the login page.","endLoc":29,"header":"def login_required(view)","id":50,"name":"login_required","nodeType":"Function","startLoc":19,"text":"def login_required(view):\n \"\"\"View decorator that redirects anonymous users to the login page.\"\"\"\n\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)\n\n return wrapped_view"},{"col":0,"comment":"null","endLoc":9,"header":"def create_app2(foo, bar)","id":51,"name":"create_app2","nodeType":"Function","startLoc":8,"text":"def create_app2(foo, bar):\n return Flask(\"_\".join([\"app2\", foo, bar]))"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":52,"name":"app2","nodeType":"Attribute","startLoc":4,"text":"app2"},{"col":0,"comment":"","endLoc":1,"header":"app.py#","id":53,"name":"","nodeType":"Function","startLoc":1,"text":"testapp = Flask(\"testapp\")"},{"col":0,"comment":"","endLoc":1,"header":"importerrorapp.py#","id":54,"name":"","nodeType":"Function","startLoc":1,"text":"raise ImportError()\n\ntestapp = Flask(\"testapp\")"},{"col":0,"comment":"","endLoc":1,"header":"multiapp.py#","id":55,"name":"","nodeType":"Function","startLoc":1,"text":"app1 = Flask(\"app1\")\n\napp2 = Flask(\"app2\")"},{"id":56,"name":"views.rst","nodeType":"TextFile","path":"docs","text":"Pluggable Views\n===============\n\n.. versionadded:: 0.7\n\nFlask 0.7 introduces pluggable views inspired by the generic views from\nDjango which are based on classes instead of functions. The main\nintention is that you can replace parts of the implementations and this\nway have customizable pluggable views.\n\nBasic Principle\n---------------\n\nConsider you have a function that loads a list of objects from the\ndatabase and renders into a template::\n\n @app.route('/users/')\n def show_users(page):\n users = User.query.all()\n return render_template('users.html', users=users)\n\nThis is simple and flexible, but if you want to provide this view in a\ngeneric fashion that can be adapted to other models and templates as well\nyou might want more flexibility. This is where pluggable class-based\nviews come into place. As the first step to convert this into a class\nbased view you would do this::\n\n\n from flask.views import View\n\n class ShowUsers(View):\n\n def dispatch_request(self):\n users = User.query.all()\n return render_template('users.html', objects=users)\n\n app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))\n\nAs you can see what you have to do is to create a subclass of\n:class:`flask.views.View` and implement\n:meth:`~flask.views.View.dispatch_request`. Then we have to convert that\nclass into an actual view function by using the\n:meth:`~flask.views.View.as_view` class method. The string you pass to\nthat function is the name of the endpoint that view will then have. But\nthis by itself is not helpful, so let's refactor the code a bit::\n\n\n from flask.views import View\n\n class ListView(View):\n\n def get_template_name(self):\n raise NotImplementedError()\n\n def render_template(self, context):\n return render_template(self.get_template_name(), **context)\n\n def dispatch_request(self):\n context = {'objects': self.get_objects()}\n return self.render_template(context)\n\n class UserView(ListView):\n\n def get_template_name(self):\n return 'users.html'\n\n def get_objects(self):\n return User.query.all()\n\nThis of course is not that helpful for such a small example, but it's good\nenough to explain the basic principle. When you have a class-based view\nthe question comes up what ``self`` points to. The way this works is that\nwhenever the request is dispatched a new instance of the class is created\nand the :meth:`~flask.views.View.dispatch_request` method is called with\nthe parameters from the URL rule. The class itself is instantiated with\nthe parameters passed to the :meth:`~flask.views.View.as_view` function.\nFor instance you can write a class like this::\n\n class RenderTemplateView(View):\n def __init__(self, template_name):\n self.template_name = template_name\n def dispatch_request(self):\n return render_template(self.template_name)\n\nAnd then you can register it like this::\n\n app.add_url_rule('/about', view_func=RenderTemplateView.as_view(\n 'about_page', template_name='about.html'))\n\nMethod Hints\n------------\n\nPluggable views are attached to the application like a regular function by\neither using :func:`~flask.Flask.route` or better\n:meth:`~flask.Flask.add_url_rule`. That however also means that you would\nhave to provide the names of the HTTP methods the view supports when you\nattach this. In order to move that information to the class you can\nprovide a :attr:`~flask.views.View.methods` attribute that has this\ninformation::\n\n class MyView(View):\n methods = ['GET', 'POST']\n\n def dispatch_request(self):\n if request.method == 'POST':\n ...\n ...\n\n app.add_url_rule('/myview', view_func=MyView.as_view('myview'))\n\nMethod Based Dispatching\n------------------------\n\nFor RESTful APIs it's especially helpful to execute a different function\nfor each HTTP method. With the :class:`flask.views.MethodView` you can\neasily do that. Each HTTP method maps to a function with the same name\n(just in lowercase)::\n\n from flask.views import MethodView\n\n class UserAPI(MethodView):\n\n def get(self):\n users = User.query.all()\n ...\n\n def post(self):\n user = User.from_form_data(request.form)\n ...\n\n app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))\n\nThat way you also don't have to provide the\n:attr:`~flask.views.View.methods` attribute. It's automatically set based\non the methods defined in the class.\n\nDecorating Views\n----------------\n\nSince the view class itself is not the view function that is added to the\nrouting system it does not make much sense to decorate the class itself.\nInstead you either have to decorate the return value of\n:meth:`~flask.views.View.as_view` by hand::\n\n def user_required(f):\n \"\"\"Checks whether user is logged in or raises error 401.\"\"\"\n def decorator(*args, **kwargs):\n if not g.user:\n abort(401)\n return f(*args, **kwargs)\n return decorator\n\n view = user_required(UserAPI.as_view('users'))\n app.add_url_rule('/users/', view_func=view)\n\nStarting with Flask 0.8 there is also an alternative way where you can\nspecify a list of decorators to apply in the class declaration::\n\n class UserAPI(MethodView):\n decorators = [user_required]\n\nDue to the implicit self from the caller's perspective you cannot use\nregular view decorators on the individual methods of the view however,\nkeep this in mind.\n\nMethod Views for APIs\n---------------------\n\nWeb APIs are often working very closely with HTTP verbs so it makes a lot\nof sense to implement such an API based on the\n:class:`~flask.views.MethodView`. That said, you will notice that the API\nwill require different URL rules that go to the same method view most of\nthe time. For instance consider that you are exposing a user object on\nthe web:\n\n=============== =============== ======================================\nURL Method Description\n--------------- --------------- --------------------------------------\n``/users/`` ``GET`` Gives a list of all users\n``/users/`` ``POST`` Creates a new user\n``/users/`` ``GET`` Shows a single user\n``/users/`` ``PUT`` Updates a single user\n``/users/`` ``DELETE`` Deletes a single user\n=============== =============== ======================================\n\nSo how would you go about doing that with the\n:class:`~flask.views.MethodView`? The trick is to take advantage of the\nfact that you can provide multiple rules to the same view.\n\nLet's assume for the moment the view would look like this::\n\n class UserAPI(MethodView):\n\n def get(self, user_id):\n if user_id is None:\n # return a list of users\n pass\n else:\n # expose a single user\n pass\n\n def post(self):\n # create a new user\n pass\n\n def delete(self, user_id):\n # delete a single user\n pass\n\n def put(self, user_id):\n # update a single user\n pass\n\nSo how do we hook this up with the routing system? By adding two rules\nand explicitly mentioning the methods for each::\n\n user_view = UserAPI.as_view('user_api')\n app.add_url_rule('/users/', defaults={'user_id': None},\n view_func=user_view, methods=['GET',])\n app.add_url_rule('/users/', view_func=user_view, methods=['POST',])\n app.add_url_rule('/users/', view_func=user_view,\n methods=['GET', 'PUT', 'DELETE'])\n\nIf you have a lot of APIs that look similar you can refactor that\nregistration code::\n\n def register_api(view, endpoint, url, pk='id', pk_type='int'):\n view_func = view.as_view(endpoint)\n app.add_url_rule(url, defaults={pk: None},\n view_func=view_func, methods=['GET',])\n app.add_url_rule(url, view_func=view_func, methods=['POST',])\n app.add_url_rule(f'{url}<{pk_type}:{pk}>', view_func=view_func,\n methods=['GET', 'PUT', 'DELETE'])\n\n register_api(UserAPI, 'user_api', '/users/', pk='user_id')\n"},{"id":57,"name":"reqcontext.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nThe Request Context\n===================\n\nThe request context keeps track of the request-level data during a\nrequest. Rather than passing the request object to each function that\nruns during a request, the :data:`request` and :data:`session` proxies\nare accessed instead.\n\nThis is similar to the :doc:`/appcontext`, which keeps track of the\napplication-level data independent of a request. A corresponding\napplication context is pushed when a request context is pushed.\n\n\nPurpose of the Context\n----------------------\n\nWhen the :class:`Flask` application handles a request, it creates a\n:class:`Request` object based on the environment it received from the\nWSGI server. Because a *worker* (thread, process, or coroutine depending\non the server) handles only one request at a time, the request data can\nbe considered global to that worker during that request. Flask uses the\nterm *context local* for this.\n\nFlask automatically *pushes* a request context when handling a request.\nView functions, error handlers, and other functions that run during a\nrequest will have access to the :data:`request` proxy, which points to\nthe request object for the current request.\n\n\nLifetime of the Context\n-----------------------\n\nWhen a Flask application begins handling a request, it pushes a request\ncontext, which also pushes an :doc:`/appcontext`. When the request ends\nit pops the request context then the application context.\n\nThe context is unique to each thread (or other worker type).\n:data:`request` cannot be passed to another thread, the other thread\nwill have a different context stack and will not know about the request\nthe parent thread was pointing to.\n\nContext locals are implemented in Werkzeug. See :doc:`werkzeug:local`\nfor more information on how this works internally.\n\n\nManually Push a Context\n-----------------------\n\nIf you try to access :data:`request`, or anything that uses it, outside\na request context, you'll get this error message:\n\n.. code-block:: pytb\n\n RuntimeError: Working outside of request context.\n\n This typically means that you attempted to use functionality that\n needed an active HTTP request. Consult the documentation on testing\n for information about how to avoid this problem.\n\nThis should typically only happen when testing code that expects an\nactive request. One option is to use the\n:meth:`test client ` to simulate a full request. Or\nyou can use :meth:`~Flask.test_request_context` in a ``with`` block, and\neverything that runs in the block will have access to :data:`request`,\npopulated with your test data. ::\n\n def generate_report(year):\n format = request.args.get('format')\n ...\n\n with app.test_request_context(\n '/make_report/2017', data={'format': 'short'}):\n generate_report()\n\nIf you see that error somewhere else in your code not related to\ntesting, it most likely indicates that you should move that code into a\nview function.\n\nFor information on how to use the request context from the interactive\nPython shell, see :doc:`/shell`.\n\n\nHow the Context Works\n---------------------\n\nThe :meth:`Flask.wsgi_app` method is called to handle each request. It\nmanages the contexts during the request. Internally, the request and\napplication contexts work as stacks, :data:`_request_ctx_stack` and\n:data:`_app_ctx_stack`. When contexts are pushed onto the stack, the\nproxies that depend on them are available and point at information from\nthe top context on the stack.\n\nWhen the request starts, a :class:`~ctx.RequestContext` is created and\npushed, which creates and pushes an :class:`~ctx.AppContext` first if\na context for that application is not already the top context. While\nthese contexts are pushed, the :data:`current_app`, :data:`g`,\n:data:`request`, and :data:`session` proxies are available to the\noriginal thread handling the request.\n\nBecause the contexts are stacks, other contexts may be pushed to change\nthe proxies during a request. While this is not a common pattern, it\ncan be used in advanced applications to, for example, do internal\nredirects or chain different applications together.\n\nAfter the request is dispatched and a response is generated and sent,\nthe request context is popped, which then pops the application context.\nImmediately before they are popped, the :meth:`~Flask.teardown_request`\nand :meth:`~Flask.teardown_appcontext` functions are executed. These\nexecute even if an unhandled exception occurred during dispatch.\n\n\n.. _callbacks-and-errors:\n\nCallbacks and Errors\n--------------------\n\nFlask dispatches a request in multiple stages which can affect the\nrequest, response, and how errors are handled. The contexts are active\nduring all of these stages.\n\nA :class:`Blueprint` can add handlers for these events that are specific\nto the blueprint. The handlers for a blueprint will run if the blueprint\nowns the route that matches the request.\n\n#. Before each request, :meth:`~Flask.before_request` functions are\n called. If one of these functions return a value, the other\n functions are skipped. The return value is treated as the response\n and the view function is not called.\n\n#. If the :meth:`~Flask.before_request` functions did not return a\n response, the view function for the matched route is called and\n returns a response.\n\n#. The return value of the view is converted into an actual response\n object and passed to the :meth:`~Flask.after_request`\n functions. Each function returns a modified or new response object.\n\n#. After the response is returned, the contexts are popped, which calls\n the :meth:`~Flask.teardown_request` and\n :meth:`~Flask.teardown_appcontext` functions. These functions are\n called even if an unhandled exception was raised at any point above.\n\nIf an exception is raised before the teardown functions, Flask tries to\nmatch it with an :meth:`~Flask.errorhandler` function to handle the\nexception and return a response. If no error handler is found, or the\nhandler itself raises an exception, Flask returns a generic\n``500 Internal Server Error`` response. The teardown functions are still\ncalled, and are passed the exception object.\n\nIf debug mode is enabled, unhandled exceptions are not converted to a\n``500`` response and instead are propagated to the WSGI server. This\nallows the development server to present the interactive debugger with\nthe traceback.\n\n\nTeardown Callbacks\n~~~~~~~~~~~~~~~~~~\n\nThe teardown callbacks are independent of the request dispatch, and are\ninstead called by the contexts when they are popped. The functions are\ncalled even if there is an unhandled exception during dispatch, and for\nmanually pushed contexts. This means there is no guarantee that any\nother parts of the request dispatch have run first. Be sure to write\nthese functions in a way that does not depend on other callbacks and\nwill not fail.\n\nDuring testing, it can be useful to defer popping the contexts after the\nrequest ends, so that their data can be accessed in the test function.\nUse the :meth:`~Flask.test_client` as a ``with`` block to preserve the\ncontexts until the ``with`` block exits.\n\n.. code-block:: python\n\n from flask import Flask, request\n\n app = Flask(__name__)\n\n @app.route('/')\n def hello():\n print('during view')\n return 'Hello, World!'\n\n @app.teardown_request\n def show_teardown(exception):\n print('after with block')\n\n with app.test_request_context():\n print('during with block')\n\n # teardown functions are called after the context with block exits\n\n with app.test_client() as client:\n client.get('/')\n # the contexts are not popped even though the request ended\n print(request.path)\n\n # the contexts are popped and teardown functions are called after\n # the client with block exits\n\nSignals\n~~~~~~~\n\nIf :data:`~signals.signals_available` is true, the following signals are\nsent:\n\n#. :data:`request_started` is sent before the\n :meth:`~Flask.before_request` functions are called.\n\n#. :data:`request_finished` is sent after the\n :meth:`~Flask.after_request` functions are called.\n\n#. :data:`got_request_exception` is sent when an exception begins to\n be handled, but before an :meth:`~Flask.errorhandler` is looked up or\n called.\n\n#. :data:`request_tearing_down` is sent after the\n :meth:`~Flask.teardown_request` functions are called.\n\n\nContext Preservation on Error\n-----------------------------\n\nAt the end of a request, the request context is popped and all data\nassociated with it is destroyed. If an error occurs during development,\nit is useful to delay destroying the data for debugging purposes.\n\nWhen the development server is running in development mode (the\n``FLASK_ENV`` environment variable is set to ``'development'``), the\nerror and data will be preserved and shown in the interactive debugger.\n\nThis behavior can be controlled with the\n:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it\ndefaults to ``True`` in the development environment.\n\nDo not enable :data:`PRESERVE_CONTEXT_ON_EXCEPTION` in production, as it\nwill cause your application to leak memory on exceptions.\n\n\n.. _notes-on-proxies:\n\nNotes On Proxies\n----------------\n\nSome of the objects provided by Flask are proxies to other objects. The\nproxies are accessed in the same way for each worker thread, but\npoint to the unique object bound to each worker behind the scenes as\ndescribed on this page.\n\nMost of the time you don't have to care about that, but there are some\nexceptions where it is good to know that this object is actually a proxy:\n\n- The proxy objects cannot fake their type as the actual object types.\n If you want to perform instance checks, you have to do that on the\n object being proxied.\n- The reference to the proxied object is needed in some situations,\n such as sending :doc:`signals` or passing data to a background\n thread.\n\nIf you need to access the underlying object that is proxied, use the\n:meth:`~werkzeug.local.LocalProxy._get_current_object` method::\n\n app = current_app._get_current_object()\n my_signal.send(app)\n"},{"id":58,"name":"tests/test_apps/subdomaintestmodule/static","nodeType":"Package"},{"id":59,"name":"hello.txt","nodeType":"TextFile","path":"tests/test_apps/subdomaintestmodule/static","text":"Hello Subdomain\n"},{"id":60,"name":"blueprints.rst","nodeType":"TextFile","path":"docs","text":"Modular Applications with Blueprints\n====================================\n\n.. currentmodule:: flask\n\n.. versionadded:: 0.7\n\nFlask uses a concept of *blueprints* for making application components and\nsupporting common patterns within an application or across applications.\nBlueprints can greatly simplify how large applications work and provide a\ncentral means for Flask extensions to register operations on applications.\nA :class:`Blueprint` object works similarly to a :class:`Flask`\napplication object, but it is not actually an application. Rather it is a\n*blueprint* of how to construct or extend an application.\n\nWhy Blueprints?\n---------------\n\nBlueprints in Flask are intended for these cases:\n\n* Factor an application into a set of blueprints. This is ideal for\n larger applications; a project could instantiate an application object,\n initialize several extensions, and register a collection of blueprints.\n* Register a blueprint on an application at a URL prefix and/or subdomain.\n Parameters in the URL prefix/subdomain become common view arguments\n (with defaults) across all view functions in the blueprint.\n* Register a blueprint multiple times on an application with different URL\n rules.\n* Provide template filters, static files, templates, and other utilities\n through blueprints. A blueprint does not have to implement applications\n or view functions.\n* Register a blueprint on an application for any of these cases when\n initializing a Flask extension.\n\nA blueprint in Flask is not a pluggable app because it is not actually an\napplication -- it's a set of operations which can be registered on an\napplication, even multiple times. Why not have multiple application\nobjects? You can do that (see :doc:`/patterns/appdispatch`), but your\napplications will have separate configs and will be managed at the WSGI\nlayer.\n\nBlueprints instead provide separation at the Flask level, share\napplication config, and can change an application object as necessary with\nbeing registered. The downside is that you cannot unregister a blueprint\nonce an application was created without having to destroy the whole\napplication object.\n\nThe Concept of Blueprints\n-------------------------\n\nThe basic concept of blueprints is that they record operations to execute\nwhen registered on an application. Flask associates view functions with\nblueprints when dispatching requests and generating URLs from one endpoint\nto another.\n\nMy First Blueprint\n------------------\n\nThis is what a very basic blueprint looks like. In this case we want to\nimplement a blueprint that does simple rendering of static templates::\n\n from flask import Blueprint, render_template, abort\n from jinja2 import TemplateNotFound\n\n simple_page = Blueprint('simple_page', __name__,\n template_folder='templates')\n\n @simple_page.route('/', defaults={'page': 'index'})\n @simple_page.route('/')\n def show(page):\n try:\n return render_template(f'pages/{page}.html')\n except TemplateNotFound:\n abort(404)\n\nWhen you bind a function with the help of the ``@simple_page.route``\ndecorator, the blueprint will record the intention of registering the\nfunction ``show`` on the application when it's later registered.\nAdditionally it will prefix the endpoint of the function with the\nname of the blueprint which was given to the :class:`Blueprint`\nconstructor (in this case also ``simple_page``). The blueprint's name\ndoes not modify the URL, only the endpoint.\n\nRegistering Blueprints\n----------------------\n\nSo how do you register that blueprint? Like this::\n\n from flask import Flask\n from yourapplication.simple_page import simple_page\n\n app = Flask(__name__)\n app.register_blueprint(simple_page)\n\nIf you check the rules registered on the application, you will find\nthese::\n\n >>> app.url_map\n Map([' (HEAD, OPTIONS, GET) -> static>,\n ' (HEAD, OPTIONS, GET) -> simple_page.show>,\n simple_page.show>])\n\nThe first one is obviously from the application itself for the static\nfiles. The other two are for the `show` function of the ``simple_page``\nblueprint. As you can see, they are also prefixed with the name of the\nblueprint and separated by a dot (``.``).\n\nBlueprints however can also be mounted at different locations::\n\n app.register_blueprint(simple_page, url_prefix='/pages')\n\nAnd sure enough, these are the generated rules::\n\n >>> app.url_map\n Map([' (HEAD, OPTIONS, GET) -> static>,\n ' (HEAD, OPTIONS, GET) -> simple_page.show>,\n simple_page.show>])\n\nOn top of that you can register blueprints multiple times though not every\nblueprint might respond properly to that. In fact it depends on how the\nblueprint is implemented if it can be mounted more than once.\n\nNesting Blueprints\n------------------\n\nIt is possible to register a blueprint on another blueprint.\n\n.. code-block:: python\n\n parent = Blueprint('parent', __name__, url_prefix='/parent')\n child = Blueprint('child', __name__, url_prefix='/child')\n parent.register_blueprint(child)\n app.register_blueprint(parent)\n\nThe child blueprint will gain the parent's name as a prefix to its\nname, and child URLs will be prefixed with the parent's URL prefix.\n\n.. code-block:: python\n\n url_for('parent.child.create')\n /parent/child/create\n\nBlueprint-specific before request functions, etc. registered with the\nparent will trigger for the child. If a child does not have an error\nhandler that can handle a given exception, the parent's will be tried.\n\n\nBlueprint Resources\n-------------------\n\nBlueprints can provide resources as well. Sometimes you might want to\nintroduce a blueprint only for the resources it provides.\n\nBlueprint Resource Folder\n`````````````````````````\n\nLike for regular applications, blueprints are considered to be contained\nin a folder. While multiple blueprints can originate from the same folder,\nit does not have to be the case and it's usually not recommended.\n\nThe folder is inferred from the second argument to :class:`Blueprint` which\nis usually `__name__`. This argument specifies what logical Python\nmodule or package corresponds to the blueprint. If it points to an actual\nPython package that package (which is a folder on the filesystem) is the\nresource folder. If it's a module, the package the module is contained in\nwill be the resource folder. You can access the\n:attr:`Blueprint.root_path` property to see what the resource folder is::\n\n >>> simple_page.root_path\n '/Users/username/TestProject/yourapplication'\n\nTo quickly open sources from this folder you can use the\n:meth:`~Blueprint.open_resource` function::\n\n with simple_page.open_resource('static/style.css') as f:\n code = f.read()\n\nStatic Files\n````````````\n\nA blueprint can expose a folder with static files by providing the path\nto the folder on the filesystem with the ``static_folder`` argument.\nIt is either an absolute path or relative to the blueprint's location::\n\n admin = Blueprint('admin', __name__, static_folder='static')\n\nBy default the rightmost part of the path is where it is exposed on the\nweb. This can be changed with the ``static_url_path`` argument. Because the\nfolder is called ``static`` here it will be available at the\n``url_prefix`` of the blueprint + ``/static``. If the blueprint\nhas the prefix ``/admin``, the static URL will be ``/admin/static``.\n\nThe endpoint is named ``blueprint_name.static``. You can generate URLs\nto it with :func:`url_for` like you would with the static folder of the\napplication::\n\n url_for('admin.static', filename='style.css')\n\nHowever, if the blueprint does not have a ``url_prefix``, it is not\npossible to access the blueprint's static folder. This is because the\nURL would be ``/static`` in this case, and the application's ``/static``\nroute takes precedence. Unlike template folders, blueprint static\nfolders are not searched if the file does not exist in the application\nstatic folder.\n\nTemplates\n`````````\n\nIf you want the blueprint to expose templates you can do that by providing\nthe `template_folder` parameter to the :class:`Blueprint` constructor::\n\n admin = Blueprint('admin', __name__, template_folder='templates')\n\nFor static files, the path can be absolute or relative to the blueprint\nresource folder.\n\nThe template folder is added to the search path of templates but with a lower\npriority than the actual application's template folder. That way you can\neasily override templates that a blueprint provides in the actual application.\nThis also means that if you don't want a blueprint template to be accidentally\noverridden, make sure that no other blueprint or actual application template\nhas the same relative path. When multiple blueprints provide the same relative\ntemplate path the first blueprint registered takes precedence over the others.\n\n\nSo if you have a blueprint in the folder ``yourapplication/admin`` and you\nwant to render the template ``'admin/index.html'`` and you have provided\n``templates`` as a `template_folder` you will have to create a file like\nthis: :file:`yourapplication/admin/templates/admin/index.html`. The reason\nfor the extra ``admin`` folder is to avoid getting our template overridden\nby a template named ``index.html`` in the actual application template\nfolder.\n\nTo further reiterate this: if you have a blueprint named ``admin`` and you\nwant to render a template called :file:`index.html` which is specific to this\nblueprint, the best idea is to lay out your templates like this::\n\n yourpackage/\n blueprints/\n admin/\n templates/\n admin/\n index.html\n __init__.py\n\nAnd then when you want to render the template, use :file:`admin/index.html` as\nthe name to look up the template by. If you encounter problems loading\nthe correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config\nvariable which will instruct Flask to print out the steps it goes through\nto locate templates on every ``render_template`` call.\n\nBuilding URLs\n-------------\n\nIf you want to link from one page to another you can use the\n:func:`url_for` function just like you normally would do just that you\nprefix the URL endpoint with the name of the blueprint and a dot (``.``)::\n\n url_for('admin.index')\n\nAdditionally if you are in a view function of a blueprint or a rendered\ntemplate and you want to link to another endpoint of the same blueprint,\nyou can use relative redirects by prefixing the endpoint with a dot only::\n\n url_for('.index')\n\nThis will link to ``admin.index`` for instance in case the current request\nwas dispatched to any other admin blueprint endpoint.\n\n\nBlueprint Error Handlers\n------------------------\n\nBlueprints support the ``errorhandler`` decorator just like the :class:`Flask`\napplication object, so it is easy to make Blueprint-specific custom error\npages.\n\nHere is an example for a \"404 Page Not Found\" exception::\n\n @simple_page.errorhandler(404)\n def page_not_found(e):\n return render_template('pages/404.html')\n\nMost errorhandlers will simply work as expected; however, there is a caveat\nconcerning handlers for 404 and 405 exceptions. These errorhandlers are only\ninvoked from an appropriate ``raise`` statement or a call to ``abort`` in another\nof the blueprint's view functions; they are not invoked by, e.g., an invalid URL\naccess. This is because the blueprint does not \"own\" a certain URL space, so\nthe application instance has no way of knowing which blueprint error handler it\nshould run if given an invalid URL. If you would like to execute different\nhandling strategies for these errors based on URL prefixes, they may be defined\nat the application level using the ``request`` proxy object::\n\n @app.errorhandler(404)\n @app.errorhandler(405)\n def _handle_api_error(ex):\n if request.path.startswith('/api/'):\n return jsonify(error=str(ex)), ex.code\n else:\n return ex\n\nSee :doc:`/errorhandling`.\n"},{"id":61,"name":"examples/tutorial/flaskr/templates","nodeType":"Package"},{"id":62,"name":"base.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates","text":"\n{% block title %}{% endblock %} - Flaskr\n\n\n
\n
\n {% block header %}{% endblock %}\n
\n {% for message in get_flashed_messages() %}\n
{{ message }}
\n {% endfor %}\n {% block content %}{% endblock %}\n
\n"},{"id":63,"name":"tests/test_apps/subdomaintestmodule","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/subdomaintestmodule","id":64,"nodeType":"File","text":"from flask import Module\n\n\nmod = Module(__name__, \"foo\", subdomain=\"foo\")\n"},{"id":65,"name":"feature-request.md","nodeType":"TextFile","path":".github/ISSUE_TEMPLATE","text":"---\nname: Feature request\nabout: Suggest a new feature for Flask\n---\n\n\n\n\n"},{"id":66,"name":"dependabot.yml","nodeType":"TextFile","path":".github","text":"version: 2\nupdates:\n- package-ecosystem: pip\n directory: \"/\"\n schedule:\n interval: monthly\n time: \"08:00\"\n open-pull-requests-limit: 99\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":67,"name":"mod","nodeType":"Attribute","startLoc":4,"text":"mod"},{"id":68,"name":"schema.sql","nodeType":"TextFile","path":"examples/tutorial/flaskr","text":"-- Initialize the database.\n-- Drop any existing data and create empty tables.\n\nDROP TABLE IF EXISTS user;\nDROP TABLE IF EXISTS post;\n\nCREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT UNIQUE NOT NULL,\n password TEXT NOT NULL\n);\n\nCREATE TABLE post (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n author_id INTEGER NOT NULL,\n created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n FOREIGN KEY (author_id) REFERENCES user (id)\n);\n"},{"id":69,"name":".github/workflows","nodeType":"Package"},{"id":70,"name":"lock.yaml","nodeType":"TextFile","path":".github/workflows","text":"name: 'Lock threads'\n\non:\n schedule:\n - cron: '0 0 * * *'\n\njobs:\n lock:\n runs-on: ubuntu-latest\n steps:\n - uses: dessant/lock-threads@v2\n with:\n github-token: ${{ github.token }}\n issue-lock-inactive-days: 14\n pr-lock-inactive-days: 14\n"},{"id":71,"name":"make.bat","nodeType":"TextFile","path":"docs","text":"@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset SOURCEDIR=.\nset BUILDDIR=_build\n\nif \"%1\" == \"\" goto help\n\n%SPHINXBUILD% >NUL 2>NUL\nif errorlevel 9009 (\n\techo.\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\n\techo.installed, then set the SPHINXBUILD environment variable to point\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\n\techo.may add the Sphinx directory to PATH.\n\techo.\n\techo.If you don't have Sphinx installed, grab it from\n\techo.http://sphinx-doc.org/\n\texit /b 1\n)\n\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\ngoto end\n\n:help\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\n\n:end\npopd\n"},{"id":72,"name":"contributing.rst","nodeType":"TextFile","path":"docs","text":".. include:: ../CONTRIBUTING.rst\n"},{"id":73,"name":"errorhandling.rst","nodeType":"TextFile","path":"docs","text":"Handling Application Errors\n===========================\n\nApplications fail, servers fail. Sooner or later you will see an exception\nin production. Even if your code is 100% correct, you will still see\nexceptions from time to time. Why? Because everything else involved will\nfail. Here are some situations where perfectly fine code can lead to server\nerrors:\n\n- the client terminated the request early and the application was still\n reading from the incoming data\n- the database server was overloaded and could not handle the query\n- a filesystem is full\n- a harddrive crashed\n- a backend server overloaded\n- a programming error in a library you are using\n- network connection of the server to another system failed\n\nAnd that's just a small sample of issues you could be facing. So how do we\ndeal with that sort of problem? By default if your application runs in\nproduction mode, and an exception is raised Flask will display a very simple\npage for you and log the exception to the :attr:`~flask.Flask.logger`.\n\nBut there is more you can do, and we will cover some better setups to deal\nwith errors including custom exceptions and 3rd party tools.\n\n\n.. _error-logging-tools:\n\nError Logging Tools\n-------------------\n\nSending error mails, even if just for critical ones, can become\noverwhelming if enough users are hitting the error and log files are\ntypically never looked at. This is why we recommend using `Sentry\n`_ for dealing with application errors. It's\navailable as a source-available project `on GitHub\n`_ and is also available as a `hosted version\n`_ which you can try for free. Sentry\naggregates duplicate errors, captures the full stack trace and local\nvariables for debugging, and sends you mails based on new errors or\nfrequency thresholds.\n\nTo use Sentry you need to install the ``sentry-sdk`` client with extra\n``flask`` dependencies.\n\n.. code-block:: text\n\n $ pip install sentry-sdk[flask]\n\nAnd then add this to your Flask app:\n\n.. code-block:: python\n\n import sentry_sdk\n from sentry_sdk.integrations.flask import FlaskIntegration\n\n sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])\n\nThe ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you\nget from your Sentry installation.\n\nAfter installation, failures leading to an Internal Server Error\nare automatically reported to Sentry and from there you can\nreceive error notifications.\n\nSee also:\n\n- Sentry also supports catching errors from a worker queue\n (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs\n `__ for more information.\n- `Getting started with Sentry `__\n- `Flask-specific documentation `__\n\n\nError Handlers\n--------------\n\nWhen an error occurs in Flask, an appropriate `HTTP status code\n`__ will be\nreturned. 400-499 indicate errors with the client's request data, or\nabout the data requested. 500-599 indicate errors with the server or\napplication itself.\n\nYou might want to show custom error pages to the user when an error occurs.\nThis can be done by registering error handlers.\n\nAn error handler is a function that returns a response when a type of error is\nraised, similar to how a view is a function that returns a response when a\nrequest URL is matched. It is passed the instance of the error being handled,\nwhich is most likely a :exc:`~werkzeug.exceptions.HTTPException`.\n\nThe status code of the response will not be set to the handler's code. Make\nsure to provide the appropriate HTTP status code when returning a response from\na handler.\n\n\nRegistering\n```````````\n\nRegister handlers by decorating a function with\n:meth:`~flask.Flask.errorhandler`. Or use\n:meth:`~flask.Flask.register_error_handler` to register the function later.\nRemember to set the error code when returning the response.\n\n.. code-block:: python\n\n @app.errorhandler(werkzeug.exceptions.BadRequest)\n def handle_bad_request(e):\n return 'bad request!', 400\n\n # or, without the decorator\n app.register_error_handler(400, handle_bad_request)\n\n:exc:`werkzeug.exceptions.HTTPException` subclasses like\n:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable\nwhen registering handlers. (``BadRequest.code == 400``)\n\nNon-standard HTTP codes cannot be registered by code because they are not known\nby Werkzeug. Instead, define a subclass of\n:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and\nregister and raise that exception class.\n\n.. code-block:: python\n\n class InsufficientStorage(werkzeug.exceptions.HTTPException):\n code = 507\n description = 'Not enough storage space.'\n\n app.register_error_handler(InsufficientStorage, handle_507)\n\n raise InsufficientStorage()\n\nHandlers can be registered for any exception class, not just\n:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status\ncodes. Handlers can be registered for a specific class, or for all subclasses\nof a parent class.\n\n\nHandling\n````````\n\nWhen building a Flask application you *will* run into exceptions. If some part\nof your code breaks while handling a request (and you have no error handlers\nregistered), a \"500 Internal Server Error\"\n(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.\nSimilarly, \"404 Not Found\"\n(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.\nIf a route receives an unallowed request method, a \"405 Method Not Allowed\"\n(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all\nsubclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by\ndefault in Flask.\n\nFlask gives you to the ability to raise any HTTP exception registered by\nWerkzeug. However, the default HTTP exceptions return simple exception\npages. You might want to show custom error pages to the user when an error occurs.\nThis can be done by registering error handlers.\n\nWhen Flask catches an exception while handling a request, it is first looked up by code.\nIf no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.\nIf no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a\ngeneric message about their code, while other exceptions are converted to a\ngeneric \"500 Internal Server Error\".\n\nFor example, if an instance of :exc:`ConnectionRefusedError` is raised,\nand a handler is registered for :exc:`ConnectionError` and\n:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`\nhandler is called with the exception instance to generate the response.\n\nHandlers registered on the blueprint take precedence over those registered\nglobally on the application, assuming a blueprint is handling the request that\nraises the exception. However, the blueprint cannot handle 404 routing errors\nbecause the 404 occurs at the routing level before the blueprint can be\ndetermined.\n\n\nGeneric Exception Handlers\n``````````````````````````\n\nIt is possible to register error handlers for very generic base classes\nsuch as ``HTTPException`` or even ``Exception``. However, be aware that\nthese will catch more than you might expect.\n\nFor example, an error handler for ``HTTPException`` might be useful for turning\nthe default HTML errors pages into JSON. However, this\nhandler will trigger for things you don't cause directly, such as 404\nand 405 errors during routing. Be sure to craft your handler carefully\nso you don't lose information about the HTTP error.\n\n.. code-block:: python\n\n from flask import json\n from werkzeug.exceptions import HTTPException\n\n @app.errorhandler(HTTPException)\n def handle_exception(e):\n \"\"\"Return JSON instead of HTML for HTTP errors.\"\"\"\n # start with the correct headers and status code from the error\n response = e.get_response()\n # replace the body with JSON\n response.data = json.dumps({\n \"code\": e.code,\n \"name\": e.name,\n \"description\": e.description,\n })\n response.content_type = \"application/json\"\n return response\n\nAn error handler for ``Exception`` might seem useful for changing how\nall errors, even unhandled ones, are presented to the user. However,\nthis is similar to doing ``except Exception:`` in Python, it will\ncapture *all* otherwise unhandled errors, including all HTTP status\ncodes.\n\nIn most cases it will be safer to register handlers for more\nspecific exceptions. Since ``HTTPException`` instances are valid WSGI\nresponses, you could also pass them through directly.\n\n.. code-block:: python\n\n from werkzeug.exceptions import HTTPException\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n # pass through HTTP errors\n if isinstance(e, HTTPException):\n return e\n\n # now you're handling non-HTTP exceptions only\n return render_template(\"500_generic.html\", e=e), 500\n\nError handlers still respect the exception class hierarchy. If you\nregister handlers for both ``HTTPException`` and ``Exception``, the\n``Exception`` handler will not handle ``HTTPException`` subclasses\nbecause it the ``HTTPException`` handler is more specific.\n\n\nUnhandled Exceptions\n````````````````````\n\nWhen there is no error handler registered for an exception, a 500\nInternal Server Error will be returned instead. See\n:meth:`flask.Flask.handle_exception` for information about this\nbehavior.\n\nIf there is an error handler registered for ``InternalServerError``,\nthis will be invoked. As of Flask 1.1.0, this error handler will always\nbe passed an instance of ``InternalServerError``, not the original\nunhandled error.\n\nThe original error is available as ``e.original_exception``.\n\nAn error handler for \"500 Internal Server Error\" will be passed uncaught\nexceptions in addition to explicit 500 errors. In debug mode, a handler\nfor \"500 Internal Server Error\" will not be used. Instead, the\ninteractive debugger will be shown.\n\n\nCustom Error Pages\n------------------\n\nSometimes when building a Flask application, you might want to raise a\n:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that\nsomething is wrong with the request. Fortunately, Flask comes with a handy\n:func:`~flask.abort` function that aborts a request with a HTTP error from\nwerkzeug as desired. It will also provide a plain black and white error page\nfor you with a basic description, but nothing fancy.\n\nDepending on the error code it is less or more likely for the user to\nactually see such an error.\n\nConsider the code below, we might have a user profile route, and if the user\nfails to pass a username we can raise a \"400 Bad Request\". If the user passes a\nusername and we can't find it, we raise a \"404 Not Found\".\n\n.. code-block:: python\n\n from flask import abort, render_template, request\n\n # a username needs to be supplied in the query args\n # a successful request would be like /profile?username=jack\n @app.route(\"/profile\")\n def user_profile():\n username = request.arg.get(\"username\")\n # if a username isn't supplied in the request, return a 400 bad request\n if username is None:\n abort(400)\n\n user = get_user(username=username)\n # if a user can't be found by their username, return 404 not found\n if user is None:\n abort(404)\n\n return render_template(\"profile.html\", user=user)\n\nHere is another example implementation for a \"404 Page Not Found\" exception:\n\n.. code-block:: python\n\n from flask import render_template\n\n @app.errorhandler(404)\n def page_not_found(e):\n # note that we set the 404 status explicitly\n return render_template('404.html'), 404\n\nWhen using :doc:`/patterns/appfactories`:\n\n.. code-block:: python\n\n from flask import Flask, render_template\n\n def page_not_found(e):\n return render_template('404.html'), 404\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.register_error_handler(404, page_not_found)\n return app\n\nAn example template might be this:\n\n.. code-block:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block title %}Page Not Found{% endblock %}\n {% block body %}\n

Page Not Found

\n

What you were looking for is just not there.\n

go somewhere nice\n {% endblock %}\n\n\nFurther Examples\n````````````````\n\nThe above examples wouldn't actually be an improvement on the default\nexception pages. We can create a custom 500.html template like this:\n\n.. code-block:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block title %}Internal Server Error{% endblock %}\n {% block body %}\n

Internal Server Error

\n

Oops... we seem to have made a mistake, sorry!

\n

Go somewhere nice instead\n {% endblock %}\n\nIt can be implemented by rendering the template on \"500 Internal Server Error\":\n\n.. code-block:: python\n\n from flask import render_template\n\n @app.errorhandler(500)\n def internal_server_error(e):\n # note that we set the 500 status explicitly\n return render_template('500.html'), 500\n\nWhen using :doc:`/patterns/appfactories`:\n\n.. code-block:: python\n\n from flask import Flask, render_template\n\n def internal_server_error(e):\n return render_template('500.html'), 500\n\n def create_app():\n app = Flask(__name__)\n app.register_error_handler(500, internal_server_error)\n return app\n\nWhen using :doc:`/blueprints`:\n\n.. code-block:: python\n\n from flask import Blueprint\n\n blog = Blueprint('blog', __name__)\n\n # as a decorator\n @blog.errorhandler(500)\n def internal_server_error(e):\n return render_template('500.html'), 500\n\n # or with register_error_handler\n blog.register_error_handler(500, internal_server_error)\n\n\nBlueprint Error Handlers\n------------------------\n\nIn :doc:`/blueprints`, most error handlers will work as expected.\nHowever, there is a caveat concerning handlers for 404 and 405\nexceptions. These error handlers are only invoked from an appropriate\n``raise`` statement or a call to ``abort`` in another of the blueprint's\nview functions; they are not invoked by, e.g., an invalid URL access.\n\nThis is because the blueprint does not \"own\" a certain URL space, so\nthe application instance has no way of knowing which blueprint error\nhandler it should run if given an invalid URL. If you would like to\nexecute different handling strategies for these errors based on URL\nprefixes, they may be defined at the application level using the\n``request`` proxy object.\n\n.. code-block:: python\n\n from flask import jsonify, render_template\n\n # at the application level\n # not the blueprint level\n @app.errorhandler(404)\n def page_not_found(e):\n # if a request is in our blog URL space\n if request.path.startswith('/blog/'):\n # we return a custom blog 404 page\n return render_template(\"blog/404.html\"), 404\n else:\n # otherwise we return our generic site-wide 404 page\n return render_template(\"404.html\"), 404\n\n @app.errorhandler(405)\n def method_not_allowed(e):\n # if a request has the wrong method to our API\n if request.path.startswith('/api/'):\n # we return a json saying so\n return jsonify(message=\"Method Not Allowed\"), 405\n else:\n # otherwise we return a generic site-wide 405 page\n return render_template(\"405.html\"), 405\n\n\nReturning API Errors as JSON\n----------------------------\n\nWhen building APIs in Flask, some developers realise that the built-in\nexceptions are not expressive enough for APIs and that the content type of\n:mimetype:`text/html` they are emitting is not very useful for API consumers.\n\nUsing the same techniques as above and :func:`~flask.json.jsonify` we can return JSON\nresponses to API errors. :func:`~flask.abort` is called\nwith a ``description`` parameter. The error handler will\nuse that as the JSON error message, and set the status code to 404.\n\n.. code-block:: python\n\n from flask import abort, jsonify\n\n @app.errorhandler(404)\n def resource_not_found(e):\n return jsonify(error=str(e)), 404\n\n @app.route(\"/cheese\")\n def get_one_cheese():\n resource = get_resource()\n\n if resource is None:\n abort(404, description=\"Resource not found\")\n\n return jsonify(resource)\n\nWe can also create custom exception classes. For instance, we can\nintroduce a new custom exception for an API that can take a proper human readable message,\na status code for the error and some optional payload to give more context\nfor the error.\n\nThis is a simple example:\n\n.. code-block:: python\n\n from flask import jsonify, request\n\n class InvalidAPIUsage(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n super().__init__()\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['message'] = self.message\n return rv\n\n @app.errorhandler(InvalidAPIUsage)\n def invalid_api_usage(e):\n return jsonify(e.to_dict())\n\n # an API app route for getting user information\n # a correct request might be /api/user?user_id=420\n @app.route(\"/api/user\")\n def user_api(user_id):\n user_id = request.arg.get(\"user_id\")\n if not user_id:\n raise InvalidAPIUsage(\"No user id provided!\")\n\n user = get_user(user_id=user_id)\n if not user:\n raise InvalidAPIUsage(\"No such user!\", status_code=404)\n\n return jsonify(user.to_dict())\n\nA view can now raise that exception with an error message. Additionally\nsome extra payload can be provided as a dictionary through the `payload`\nparameter.\n\n\nLogging\n-------\n\nSee :doc:`/logging` for information about how to log exceptions, such as\nby emailing them to admins.\n\n\nDebugging\n---------\n\nSee :doc:`/debugging` for information about how to debug errors in\ndevelopment and production.\n"},{"id":74,"name":"signals.rst","nodeType":"TextFile","path":"docs","text":"Signals\n=======\n\n.. versionadded:: 0.6\n\nStarting with Flask 0.6, there is integrated support for signalling in\nFlask. This support is provided by the excellent `blinker`_ library and\nwill gracefully fall back if it is not available.\n\nWhat are signals? Signals help you decouple applications by sending\nnotifications when actions occur elsewhere in the core framework or\nanother Flask extensions. In short, signals allow certain senders to\nnotify subscribers that something happened.\n\nFlask comes with a couple of signals and other extensions might provide\nmore. Also keep in mind that signals are intended to notify subscribers\nand should not encourage subscribers to modify data. You will notice that\nthere are signals that appear to do the same thing like some of the\nbuiltin decorators do (eg: :data:`~flask.request_started` is very similar\nto :meth:`~flask.Flask.before_request`). However, there are differences in\nhow they work. The core :meth:`~flask.Flask.before_request` handler, for\nexample, is executed in a specific order and is able to abort the request\nearly by returning a response. In contrast all signal handlers are\nexecuted in undefined order and do not modify any data.\n\nThe big advantage of signals over handlers is that you can safely\nsubscribe to them for just a split second. These temporary\nsubscriptions are helpful for unit testing for example. Say you want to\nknow what templates were rendered as part of a request: signals allow you\nto do exactly that.\n\nSubscribing to Signals\n----------------------\n\nTo subscribe to a signal, you can use the\n:meth:`~blinker.base.Signal.connect` method of a signal. The first\nargument is the function that should be called when the signal is emitted,\nthe optional second argument specifies a sender. To unsubscribe from a\nsignal, you can use the :meth:`~blinker.base.Signal.disconnect` method.\n\nFor all core Flask signals, the sender is the application that issued the\nsignal. When you subscribe to a signal, be sure to also provide a sender\nunless you really want to listen for signals from all applications. This is\nespecially true if you are developing an extension.\n\nFor example, here is a helper context manager that can be used in a unit test\nto determine which templates were rendered and what variables were passed\nto the template::\n\n from flask import template_rendered\n from contextlib import contextmanager\n\n @contextmanager\n def captured_templates(app):\n recorded = []\n def record(sender, template, context, **extra):\n recorded.append((template, context))\n template_rendered.connect(record, app)\n try:\n yield recorded\n finally:\n template_rendered.disconnect(record, app)\n\nThis can now easily be paired with a test client::\n\n with captured_templates(app) as templates:\n rv = app.test_client().get('/')\n assert rv.status_code == 200\n assert len(templates) == 1\n template, context = templates[0]\n assert template.name == 'index.html'\n assert len(context['items']) == 10\n\nMake sure to subscribe with an extra ``**extra`` argument so that your\ncalls don't fail if Flask introduces new arguments to the signals.\n\nAll the template rendering in the code issued by the application `app`\nin the body of the ``with`` block will now be recorded in the `templates`\nvariable. Whenever a template is rendered, the template object as well as\ncontext are appended to it.\n\nAdditionally there is a convenient helper method\n(:meth:`~blinker.base.Signal.connected_to`) that allows you to\ntemporarily subscribe a function to a signal with a context manager on\nits own. Because the return value of the context manager cannot be\nspecified that way, you have to pass the list in as an argument::\n\n from flask import template_rendered\n\n def captured_templates(app, recorded, **extra):\n def record(sender, template, context):\n recorded.append((template, context))\n return template_rendered.connected_to(record, app)\n\nThe example above would then look like this::\n\n templates = []\n with captured_templates(app, templates, **extra):\n ...\n template, context = templates[0]\n\n.. admonition:: Blinker API Changes\n\n The :meth:`~blinker.base.Signal.connected_to` method arrived in Blinker\n with version 1.1.\n\nCreating Signals\n----------------\n\nIf you want to use signals in your own application, you can use the\nblinker library directly. The most common use case are named signals in a\ncustom :class:`~blinker.base.Namespace`.. This is what is recommended\nmost of the time::\n\n from blinker import Namespace\n my_signals = Namespace()\n\nNow you can create new signals like this::\n\n model_saved = my_signals.signal('model-saved')\n\nThe name for the signal here makes it unique and also simplifies\ndebugging. You can access the name of the signal with the\n:attr:`~blinker.base.NamedSignal.name` attribute.\n\n.. admonition:: For Extension Developers\n\n If you are writing a Flask extension and you want to gracefully degrade for\n missing blinker installations, you can do so by using the\n :class:`flask.signals.Namespace` class.\n\n.. _signals-sending:\n\nSending Signals\n---------------\n\nIf you want to emit a signal, you can do so by calling the\n:meth:`~blinker.base.Signal.send` method. It accepts a sender as first\nargument and optionally some keyword arguments that are forwarded to the\nsignal subscribers::\n\n class Model(object):\n ...\n\n def save(self):\n model_saved.send(self)\n\nTry to always pick a good sender. If you have a class that is emitting a\nsignal, pass ``self`` as sender. If you are emitting a signal from a random\nfunction, you can pass ``current_app._get_current_object()`` as sender.\n\n.. admonition:: Passing Proxies as Senders\n\n Never pass :data:`~flask.current_app` as sender to a signal. Use\n ``current_app._get_current_object()`` instead. The reason for this is\n that :data:`~flask.current_app` is a proxy and not the real application\n object.\n\n\nSignals and Flask's Request Context\n-----------------------------------\n\nSignals fully support :doc:`reqcontext` when receiving signals.\nContext-local variables are consistently available between\n:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can\nrely on :class:`flask.g` and others as needed. Note the limitations described\nin :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.\n\n\nDecorator Based Signal Subscriptions\n------------------------------------\n\nWith Blinker 1.1 you can also easily subscribe to signals by using the new\n:meth:`~blinker.base.NamedSignal.connect_via` decorator::\n\n from flask import template_rendered\n\n @template_rendered.connect_via(app)\n def when_template_rendered(sender, template, context, **extra):\n print f'Template {template.name} is rendered with {context}'\n\nCore Signals\n------------\n\nTake a look at :ref:`core-signals-list` for a list of all builtin signals.\n\n\n.. _blinker: https://pypi.org/project/blinker/\n"},{"id":75,"name":"appcontext.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nThe Application Context\n=======================\n\nThe application context keeps track of the application-level data during\na request, CLI command, or other activity. Rather than passing the\napplication around to each function, the :data:`current_app` and\n:data:`g` proxies are accessed instead.\n\nThis is similar to the :doc:`/reqcontext`, which keeps track of\nrequest-level data during a request. A corresponding application context\nis pushed when a request context is pushed.\n\nPurpose of the Context\n----------------------\n\nThe :class:`Flask` application object has attributes, such as\n:attr:`~Flask.config`, that are useful to access within views and\n:doc:`CLI commands `. However, importing the ``app`` instance\nwithin the modules in your project is prone to circular import issues.\nWhen using the :doc:`app factory pattern ` or\nwriting reusable :doc:`blueprints ` or\n:doc:`extensions ` there won't be an ``app`` instance to\nimport at all.\n\nFlask solves this issue with the *application context*. Rather than\nreferring to an ``app`` directly, you use the :data:`current_app`\nproxy, which points to the application handling the current activity.\n\nFlask automatically *pushes* an application context when handling a\nrequest. View functions, error handlers, and other functions that run\nduring a request will have access to :data:`current_app`.\n\nFlask will also automatically push an app context when running CLI\ncommands registered with :attr:`Flask.cli` using ``@app.cli.command()``.\n\n\nLifetime of the Context\n-----------------------\n\nThe application context is created and destroyed as necessary. When a\nFlask application begins handling a request, it pushes an application\ncontext and a :doc:`request context `. When the request\nends it pops the request context then the application context.\nTypically, an application context will have the same lifetime as a\nrequest.\n\nSee :doc:`/reqcontext` for more information about how the contexts work\nand the full life cycle of a request.\n\n\nManually Push a Context\n-----------------------\n\nIf you try to access :data:`current_app`, or anything that uses it,\noutside an application context, you'll get this error message:\n\n.. code-block:: pytb\n\n RuntimeError: Working outside of application context.\n\n This typically means that you attempted to use functionality that\n needed to interface with the current application object in some way.\n To solve this, set up an application context with app.app_context().\n\nIf you see that error while configuring your application, such as when\ninitializing an extension, you can push a context manually since you\nhave direct access to the ``app``. Use :meth:`~Flask.app_context` in a\n``with`` block, and everything that runs in the block will have access\nto :data:`current_app`. ::\n\n def create_app():\n app = Flask(__name__)\n\n with app.app_context():\n init_db()\n\n return app\n\nIf you see that error somewhere else in your code not related to\nconfiguring the application, it most likely indicates that you should\nmove that code into a view function or CLI command.\n\n\nStoring Data\n------------\n\nThe application context is a good place to store common data during a\nrequest or CLI command. Flask provides the :data:`g object ` for this\npurpose. It is a simple namespace object that has the same lifetime as\nan application context.\n\n.. note::\n The ``g`` name stands for \"global\", but that is referring to the\n data being global *within a context*. The data on ``g`` is lost\n after the context ends, and it is not an appropriate place to store\n data between requests. Use the :data:`session` or a database to\n store data across requests.\n\nA common use for :data:`g` is to manage resources during a request.\n\n1. ``get_X()`` creates resource ``X`` if it does not exist, caching it\n as ``g.X``.\n2. ``teardown_X()`` closes or otherwise deallocates the resource if it\n exists. It is registered as a :meth:`~Flask.teardown_appcontext`\n handler.\n\nFor example, you can manage a database connection using this pattern::\n\n from flask import g\n\n def get_db():\n if 'db' not in g:\n g.db = connect_to_database()\n\n return g.db\n\n @app.teardown_appcontext\n def teardown_db(exception):\n db = g.pop('db', None)\n\n if db is not None:\n db.close()\n\nDuring a request, every call to ``get_db()`` will return the same\nconnection, and it will be closed automatically at the end of the\nrequest.\n\nYou can use :class:`~werkzeug.local.LocalProxy` to make a new context\nlocal from ``get_db()``::\n\n from werkzeug.local import LocalProxy\n db = LocalProxy(get_db)\n\nAccessing ``db`` will call ``get_db`` internally, in the same way that\n:data:`current_app` works.\n\n----\n\nIf you're writing an extension, :data:`g` should be reserved for user\ncode. You may store internal data on the context itself, but be sure to\nuse a sufficiently unique name. The current context is accessed with\n:data:`_app_ctx_stack.top <_app_ctx_stack>`. For more information see\n:doc:`/extensiondev`.\n\n\nEvents and Signals\n------------------\n\nThe application will call functions registered with\n:meth:`~Flask.teardown_appcontext` when the application context is\npopped.\n\nIf :data:`~signals.signals_available` is true, the following signals are\nsent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and\n:data:`appcontext_popped`.\n"},{"id":76,"name":"tests/test_apps/helloworld","nodeType":"Package"},{"fileName":"hello.py","filePath":"tests/test_apps/helloworld","id":77,"nodeType":"File","text":"from flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n"},{"col":0,"comment":"null","endLoc":8,"header":"@app.route(\"/\")\ndef hello()","id":78,"name":"hello","nodeType":"Function","startLoc":6,"text":"@app.route(\"/\")\ndef hello():\n return \"Hello World!\""},{"id":79,"name":"tests/test_apps","nodeType":"Package"},{"id":80,"name":".env","nodeType":"TextFile","path":"tests/test_apps","text":"FOO=env\nSPAM=1\nEGGS=2\nHAM=火腿\n"},{"col":0,"comment":"null","endLoc":13,"header":"def no_app()","id":81,"name":"no_app","nodeType":"Function","startLoc":12,"text":"def no_app():\n pass"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":82,"name":"","nodeType":"Function","startLoc":1,"text":"mod = Module(__name__, \"foo\", subdomain=\"foo\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":83,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"col":0,"comment":"","endLoc":1,"header":"hello.py#","id":84,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)"},{"id":85,"name":".flaskenv","nodeType":"TextFile","path":"tests/test_apps","text":"FOO=flaskenv\nBAR=bar\nEGGS=0\n"},{"fileName":"setup.py","filePath":"","id":86,"nodeType":"File","text":"from setuptools import setup\n\n# Metadata goes in setup.cfg. These are here for GitHub's dependency graph.\nsetup(\n name=\"Flask\",\n install_requires=[\n \"Werkzeug>=2.0\",\n \"Jinja2>=3.0\",\n \"itsdangerous>=2.0\",\n \"click>=7.1.2\",\n ],\n extras_require={\n \"async\": [\"asgiref>=3.2\"],\n \"dotenv\": [\"python-dotenv\"],\n },\n)\n"},{"col":0,"comment":"","endLoc":1,"header":"setup.py#","id":87,"name":"","nodeType":"Function","startLoc":1,"text":"setup(\n name=\"Flask\",\n install_requires=[\n \"Werkzeug>=2.0\",\n \"Jinja2>=3.0\",\n \"itsdangerous>=2.0\",\n \"click>=7.1.2\",\n ],\n extras_require={\n \"async\": [\"asgiref>=3.2\"],\n \"dotenv\": [\"python-dotenv\"],\n },\n)"},{"id":88,"name":"examples/tutorial/flaskr/templates/blog","nodeType":"Package"},{"id":89,"name":"create.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/blog","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}New Post{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n{% endblock %}\n"},{"id":90,"name":"src/flask/json","nodeType":"Package"},{"fileName":"__init__.py","filePath":"src/flask/json","id":91,"nodeType":"File","text":"import io\nimport json as _json\nimport typing as t\nimport uuid\nimport warnings\nfrom datetime import date\n\nfrom jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps\nfrom werkzeug.http import http_date\n\nfrom ..globals import current_app\nfrom ..globals import request\n\nif t.TYPE_CHECKING:\n from ..app import Flask\n from ..wrappers import Response\n\ntry:\n import dataclasses\nexcept ImportError:\n # Python < 3.7\n dataclasses = None # type: ignore\n\n\nclass JSONEncoder(_json.JSONEncoder):\n \"\"\"The default JSON encoder. Handles extra types compared to the\n built-in :class:`json.JSONEncoder`.\n\n - :class:`datetime.datetime` and :class:`datetime.date` are\n serialized to :rfc:`822` strings. This is the same as the HTTP\n date format.\n - :class:`uuid.UUID` is serialized to a string.\n - :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n - :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n\n Assign a subclass of this to :attr:`flask.Flask.json_encoder` or\n :attr:`flask.Blueprint.json_encoder` to override the default.\n \"\"\"\n\n def default(self, o: t.Any) -> t.Any:\n \"\"\"Convert ``o`` to a JSON serializable type. See\n :meth:`json.JSONEncoder.default`. Python does not support\n overriding how basic types like ``str`` or ``list`` are\n serialized, they are handled before this method.\n \"\"\"\n if isinstance(o, date):\n return http_date(o)\n if isinstance(o, uuid.UUID):\n return str(o)\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o)\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n return super().default(o)\n\n\nclass JSONDecoder(_json.JSONDecoder):\n \"\"\"The default JSON decoder.\n\n This does not change any behavior from the built-in\n :class:`json.JSONDecoder`.\n\n Assign a subclass of this to :attr:`flask.Flask.json_decoder` or\n :attr:`flask.Blueprint.json_decoder` to override the default.\n \"\"\"\n\n\ndef _dump_arg_defaults(\n kwargs: t.Dict[str, t.Any], app: t.Optional[\"Flask\"] = None\n) -> None:\n \"\"\"Inject default arguments for dump functions.\"\"\"\n if app is None:\n app = current_app\n\n if app:\n cls = app.json_encoder\n bp = app.blueprints.get(request.blueprint) if request else None # type: ignore\n if bp is not None and bp.json_encoder is not None:\n cls = bp.json_encoder\n\n kwargs.setdefault(\"cls\", cls)\n kwargs.setdefault(\"ensure_ascii\", app.config[\"JSON_AS_ASCII\"])\n kwargs.setdefault(\"sort_keys\", app.config[\"JSON_SORT_KEYS\"])\n else:\n kwargs.setdefault(\"sort_keys\", True)\n kwargs.setdefault(\"cls\", JSONEncoder)\n\n\ndef _load_arg_defaults(\n kwargs: t.Dict[str, t.Any], app: t.Optional[\"Flask\"] = None\n) -> None:\n \"\"\"Inject default arguments for load functions.\"\"\"\n if app is None:\n app = current_app\n\n if app:\n cls = app.json_decoder\n bp = app.blueprints.get(request.blueprint) if request else None # type: ignore\n if bp is not None and bp.json_decoder is not None:\n cls = bp.json_decoder\n\n kwargs.setdefault(\"cls\", cls)\n else:\n kwargs.setdefault(\"cls\", JSONDecoder)\n\n\ndef dumps(obj: t.Any, app: t.Optional[\"Flask\"] = None, **kwargs: t.Any) -> str:\n \"\"\"Serialize an object to a string of JSON.\n\n Takes the same arguments as the built-in :func:`json.dumps`, with\n some defaults from application configuration.\n\n :param obj: Object to serialize to JSON.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.dumps`.\n\n .. versionchanged:: 2.0\n ``encoding`` is deprecated and will be removed in Flask 2.1.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n _dump_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n rv = _json.dumps(obj, **kwargs)\n\n if encoding is not None:\n warnings.warn(\n \"'encoding' is deprecated and will be removed in Flask 2.1.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n if isinstance(rv, str):\n return rv.encode(encoding) # type: ignore\n\n return rv\n\n\ndef dump(\n obj: t.Any, fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any\n) -> None:\n \"\"\"Serialize an object to JSON written to a file object.\n\n Takes the same arguments as the built-in :func:`json.dump`, with\n some defaults from application configuration.\n\n :param obj: Object to serialize to JSON.\n :param fp: File object to write JSON to.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.dump`.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, is\n deprecated and will be removed in Flask 2.1.\n \"\"\"\n _dump_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n show_warning = encoding is not None\n\n try:\n fp.write(\"\")\n except TypeError:\n show_warning = True\n fp = io.TextIOWrapper(fp, encoding or \"utf-8\") # type: ignore\n\n if show_warning:\n warnings.warn(\n \"Writing to a binary file, and the 'encoding' argument, is\"\n \" deprecated and will be removed in Flask 2.1.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n _json.dump(obj, fp, **kwargs)\n\n\ndef loads(s: str, app: t.Optional[\"Flask\"] = None, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize an object from a string of JSON.\n\n Takes the same arguments as the built-in :func:`json.loads`, with\n some defaults from application configuration.\n\n :param s: JSON string to deserialize.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.loads`.\n\n .. versionchanged:: 2.0\n ``encoding`` is deprecated and will be removed in Flask 2.1. The\n data must be a string or UTF-8 bytes.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n _load_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n\n if encoding is not None:\n warnings.warn(\n \"'encoding' is deprecated and will be removed in Flask 2.1.\"\n \" The data must be a string or UTF-8 bytes.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n if isinstance(s, bytes):\n s = s.decode(encoding)\n\n return _json.loads(s, **kwargs)\n\n\ndef load(fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize an object from JSON read from a file object.\n\n Takes the same arguments as the built-in :func:`json.load`, with\n some defaults from application configuration.\n\n :param fp: File object to read JSON from.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.load`.\n\n .. versionchanged:: 2.0\n ``encoding`` is deprecated and will be removed in Flask 2.1. The\n file must be text mode, or binary mode with UTF-8 bytes.\n \"\"\"\n _load_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n\n if encoding is not None:\n warnings.warn(\n \"'encoding' is deprecated and will be removed in Flask 2.1.\"\n \" The file must be text mode, or binary mode with UTF-8\"\n \" bytes.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n if isinstance(fp.read(0), bytes):\n fp = io.TextIOWrapper(fp, encoding) # type: ignore\n\n return _json.load(fp, **kwargs)\n\n\ndef htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize an object to a string of JSON with :func:`dumps`, then\n replace HTML-unsafe characters with Unicode escapes and mark the\n result safe with :class:`~markupsafe.Markup`.\n\n This is available in templates as the ``|tojson`` filter.\n\n The returned string is safe to render in HTML documents and\n ``\n{% endblock %}\n"},{"id":320,"name":"fetch.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"{% extends 'base.html' %}\n\n{% block intro %}\n fetch\n is the new plain JavaScript way to make requests. It's\n supported in all modern browsers except IE, which requires a\n polyfill.\n{% endblock %}\n\n{% block script %}\n \n \n \n{% endblock %}\n"},{"id":321,"name":"fileuploads.rst","nodeType":"TextFile","path":"docs/patterns","text":"Uploading Files\n===============\n\nAh yes, the good old problem of file uploads. The basic idea of file\nuploads is actually quite simple. It basically works like this:\n\n1. A ``
`` tag is marked with ``enctype=multipart/form-data``\n and an ```` is placed in that form.\n2. The application accesses the file from the :attr:`~flask.request.files`\n dictionary on the request object.\n3. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save\n the file permanently somewhere on the filesystem.\n\nA Gentle Introduction\n---------------------\n\nLet's start with a very basic application that uploads a file to a\nspecific upload folder and displays a file to the user. Let's look at the\nbootstrapping code for our application::\n\n import os\n from flask import Flask, flash, request, redirect, url_for\n from werkzeug.utils import secure_filename\n\n UPLOAD_FOLDER = '/path/to/the/uploads'\n ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}\n\n app = Flask(__name__)\n app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nSo first we need a couple of imports. Most should be straightforward, the\n:func:`werkzeug.secure_filename` is explained a little bit later. The\n``UPLOAD_FOLDER`` is where we will store the uploaded files and the\n``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.\n\nWhy do we limit the extensions that are allowed? You probably don't want\nyour users to be able to upload everything there if the server is directly\nsending out the data to the client. That way you can make sure that users\nare not able to upload HTML files that would cause XSS problems (see\n:ref:`security-xss`). Also make sure to disallow ``.php`` files if the server\nexecutes them, but who has PHP installed on their server, right? :)\n\nNext the functions that check if an extension is valid and that uploads\nthe file and redirects the user to the URL for the uploaded file::\n\n def allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n @app.route('/', methods=['GET', 'POST'])\n def upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # If the user does not select a file, the browser submits an\n # empty file without a filename.\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('download_file', name=filename))\n return '''\n \n Upload new File\n

Upload new File

\n \n \n \n
\n '''\n\nSo what does that :func:`~werkzeug.utils.secure_filename` function actually do?\nNow the problem is that there is that principle called \"never trust user\ninput\". This is also true for the filename of an uploaded file. All\nsubmitted form data can be forged, and filenames can be dangerous. For\nthe moment just remember: always use that function to secure a filename\nbefore storing it directly on the filesystem.\n\n.. admonition:: Information for the Pros\n\n So you're interested in what that :func:`~werkzeug.utils.secure_filename`\n function does and what the problem is if you're not using it? So just\n imagine someone would send the following information as `filename` to\n your application::\n\n filename = \"../../../../home/username/.bashrc\"\n\n Assuming the number of ``../`` is correct and you would join this with\n the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on\n the server's filesystem he or she should not modify. This does require some\n knowledge about how the application looks like, but trust me, hackers\n are patient :)\n\n Now let's look how that function works:\n\n >>> secure_filename('../../../../home/username/.bashrc')\n 'home_username_.bashrc'\n\nWe want to be able to serve the uploaded files so they can be downloaded\nby users. We'll define a ``download_file`` view to serve files in the\nupload folder by name. ``url_for(\"download_file\", name=name)`` generates\ndownload URLs.\n\n.. code-block:: python\n\n from flask import send_from_directory\n\n @app.route('/uploads/')\n def download_file(name):\n return send_from_directory(app.config[\"UPLOAD_FOLDER\"], name)\n\nIf you're using middleware or the HTTP server to serve files, you can\nregister the ``download_file`` endpoint as ``build_only`` so ``url_for``\nwill work without a view function.\n\n.. code-block:: python\n\n app.add_url_rule(\n \"/uploads/\", endpoint=\"download_file\", build_only=True\n )\n\n\nImproving Uploads\n-----------------\n\n.. versionadded:: 0.6\n\nSo how exactly does Flask handle uploads? Well it will store them in the\nwebserver's memory if the files are reasonably small, otherwise in a\ntemporary location (as returned by :func:`tempfile.gettempdir`). But how\ndo you specify the maximum file size after which an upload is aborted? By\ndefault Flask will happily accept file uploads with an unlimited amount of\nmemory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``\nconfig key::\n\n from flask import Flask, Request\n\n app = Flask(__name__)\n app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000\n\nThe code above will limit the maximum allowed payload to 16 megabytes.\nIf a larger file is transmitted, Flask will raise a\n:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.\n\n.. admonition:: Connection Reset Issue\n\n When using the local development server, you may get a connection\n reset error instead of a 413 response. You will get the correct\n status response when running the app with a production WSGI server.\n\nThis feature was added in Flask 0.6 but can be achieved in older versions\nas well by subclassing the request object. For more information on that\nconsult the Werkzeug documentation on file handling.\n\n\nUpload Progress Bars\n--------------------\n\nA while ago many developers had the idea to read the incoming file in\nsmall chunks and store the upload progress in the database to be able to\npoll the progress with JavaScript from the client. The client asks the\nserver every 5 seconds how much it has transmitted, but this is\nsomething it should already know.\n\nAn Easier Solution\n------------------\n\nNow there are better solutions that work faster and are more reliable. There\nare JavaScript libraries like jQuery_ that have form plugins to ease the\nconstruction of progress bar.\n\nBecause the common pattern for file uploads exists almost unchanged in all\napplications dealing with uploads, there is also a Flask extension called\n`Flask-Uploads`_ that implements a full fledged upload mechanism that\nallows controlling which file extensions are allowed to be uploaded.\n\n.. _jQuery: https://jquery.com/\n.. _Flask-Uploads: https://flask-uploads.readthedocs.io/en/latest/\n"},{"col":4,"comment":"Iterates over all blueprints by the order they were registered.\n\n .. versionadded:: 0.11\n ","endLoc":1030,"header":"def iter_blueprints(self) -> t.ValuesView[\"Blueprint\"]","id":322,"name":"iter_blueprints","nodeType":"Function","startLoc":1025,"text":"def iter_blueprints(self) -> t.ValuesView[\"Blueprint\"]:\n \"\"\"Iterates over all blueprints by the order they were registered.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.blueprints.values()"},{"id":323,"name":"tests/test_apps/cliapp/inner1","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/cliapp/inner1","id":324,"nodeType":"File","text":"from flask import Flask\n\napplication = Flask(__name__)\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":325,"name":"application","nodeType":"Attribute","startLoc":3,"text":"application"},{"col":4,"comment":"A decorator that is used to register custom template filter.\n You can specify a name for the filter, otherwise the function\n name will be used. Example::\n\n @app.template_filter()\n def reverse(s):\n return s[::-1]\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n ","endLoc":1109,"header":"@setupmethod\n def template_filter(self, name: t.Optional[str] = None) -> t.Callable","id":326,"name":"template_filter","nodeType":"Function","startLoc":1091,"text":"@setupmethod\n def template_filter(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register custom template filter.\n You can specify a name for the filter, otherwise the function\n name will be used. Example::\n\n @app.template_filter()\n def reverse(s):\n return s[::-1]\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:\n self.add_template_filter(f, name=name)\n return f\n\n return decorator"},{"col":4,"comment":"Register a custom template filter. Works exactly like the\n :meth:`template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n ","endLoc":1121,"header":"@setupmethod\n def add_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None","id":327,"name":"add_template_filter","nodeType":"Function","startLoc":1111,"text":"@setupmethod\n def add_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template filter. Works exactly like the\n :meth:`template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.filters[name or f.__name__] = f"},{"col":4,"comment":"A decorator that is used to register custom template test.\n You can specify a name for the test, otherwise the function\n name will be used. Example::\n\n @app.template_test()\n def is_prime(n):\n if n == 2:\n return True\n for i in range(2, int(math.ceil(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n ","endLoc":1148,"header":"@setupmethod\n def template_test(self, name: t.Optional[str] = None) -> t.Callable","id":328,"name":"template_test","nodeType":"Function","startLoc":1123,"text":"@setupmethod\n def template_test(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register custom template test.\n You can specify a name for the test, otherwise the function\n name will be used. Example::\n\n @app.template_test()\n def is_prime(n):\n if n == 2:\n return True\n for i in range(2, int(math.ceil(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateTestCallable) -> TemplateTestCallable:\n self.add_template_test(f, name=name)\n return f\n\n return decorator"},{"col":4,"comment":"Register a custom template test. Works exactly like the\n :meth:`template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n ","endLoc":1162,"header":"@setupmethod\n def add_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None","id":329,"name":"add_template_test","nodeType":"Function","startLoc":1150,"text":"@setupmethod\n def add_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template test. Works exactly like the\n :meth:`template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.tests[name or f.__name__] = f"},{"col":4,"comment":"A decorator that is used to register a custom template global function.\n You can specify a name for the global function, otherwise the function\n name will be used. Example::\n\n @app.template_global()\n def double(n):\n return 2 * n\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n ","endLoc":1184,"header":"@setupmethod\n def template_global(self, name: t.Optional[str] = None) -> t.Callable","id":330,"name":"template_global","nodeType":"Function","startLoc":1164,"text":"@setupmethod\n def template_global(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register a custom template global function.\n You can specify a name for the global function, otherwise the function\n name will be used. Example::\n\n @app.template_global()\n def double(n):\n return 2 * n\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:\n self.add_template_global(f, name=name)\n return f\n\n return decorator"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":331,"name":"","nodeType":"Function","startLoc":1,"text":"application = Flask(__name__)"},{"id":332,"name":"wtforms.rst","nodeType":"TextFile","path":"docs/patterns","text":"Form Validation with WTForms\n============================\n\nWhen you have to work with form data submitted by a browser view, code\nquickly becomes very hard to read. There are libraries out there designed\nto make this process easier to manage. One of them is `WTForms`_ which we\nwill handle here. If you find yourself in the situation of having many\nforms, you might want to give it a try.\n\nWhen you are working with WTForms you have to define your forms as classes\nfirst. I recommend breaking up the application into multiple modules\n(:doc:`packages`) for that and adding a separate module for the\nforms.\n\n.. admonition:: Getting the most out of WTForms with an Extension\n\n The `Flask-WTF`_ extension expands on this pattern and adds a\n few little helpers that make working with forms and Flask more\n fun. You can get it from `PyPI\n `_.\n\n.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/\n\nThe Forms\n---------\n\nThis is an example form for a typical registration page::\n\n from wtforms import Form, BooleanField, StringField, PasswordField, validators\n\n class RegistrationForm(Form):\n username = StringField('Username', [validators.Length(min=4, max=25)])\n email = StringField('Email Address', [validators.Length(min=6, max=35)])\n password = PasswordField('New Password', [\n validators.DataRequired(),\n validators.EqualTo('confirm', message='Passwords must match')\n ])\n confirm = PasswordField('Repeat Password')\n accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])\n\nIn the View\n-----------\n\nIn the view function, the usage of this form looks like this::\n\n @app.route('/register', methods=['GET', 'POST'])\n def register():\n form = RegistrationForm(request.form)\n if request.method == 'POST' and form.validate():\n user = User(form.username.data, form.email.data,\n form.password.data)\n db_session.add(user)\n flash('Thanks for registering')\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\nNotice we're implying that the view is using SQLAlchemy here\n(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt\nthe code as necessary.\n\nThings to remember:\n\n1. create the form from the request :attr:`~flask.request.form` value if\n the data is submitted via the HTTP ``POST`` method and\n :attr:`~flask.request.args` if the data is submitted as ``GET``.\n2. to validate the data, call the :func:`~wtforms.form.Form.validate`\n method, which will return ``True`` if the data validates, ``False``\n otherwise.\n3. to access individual values from the form, access `form..data`.\n\nForms in Templates\n------------------\n\nNow to the template side. When you pass the form to the templates, you can\neasily render them there. Look at the following example template to see\nhow easy this is. WTForms does half the form generation for us already.\nTo make it even nicer, we can write a macro that renders a field with\nlabel and a list of errors if there are any.\n\nHere's an example :file:`_formhelpers.html` template with such a macro:\n\n.. sourcecode:: html+jinja\n\n {% macro render_field(field) %}\n
{{ field.label }}\n
{{ field(**kwargs)|safe }}\n {% if field.errors %}\n
    \n {% for error in field.errors %}\n
  • {{ error }}
  • \n {% endfor %}\n
\n {% endif %}\n
\n {% endmacro %}\n\nThis macro accepts a couple of keyword arguments that are forwarded to\nWTForm's field function, which renders the field for us. The keyword\narguments will be inserted as HTML attributes. So, for example, you can\ncall ``render_field(form.username, class='username')`` to add a class to\nthe input element. Note that WTForms returns standard Python strings,\nso we have to tell Jinja2 that this data is already HTML-escaped with\nthe ``|safe`` filter.\n\nHere is the :file:`register.html` template for the function we used above, which\ntakes advantage of the :file:`_formhelpers.html` template:\n\n.. sourcecode:: html+jinja\n\n {% from \"_formhelpers.html\" import render_field %}\n
\n
\n {{ render_field(form.username) }}\n {{ render_field(form.email) }}\n {{ render_field(form.password) }}\n {{ render_field(form.confirm) }}\n {{ render_field(form.accept_tos) }}\n
\n

\n

\n\nFor more information about WTForms, head over to the `WTForms\nwebsite`_.\n\n.. _WTForms: https://wtforms.readthedocs.io/\n.. _WTForms website: https://wtforms.readthedocs.io/\n"},{"col":4,"comment":"Register a custom template global function. Works exactly like the\n :meth:`template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n ","endLoc":1198,"header":"@setupmethod\n def add_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None","id":334,"name":"add_template_global","nodeType":"Function","startLoc":1186,"text":"@setupmethod\n def add_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template global function. Works exactly like the\n :meth:`template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.globals[name or f.__name__] = f"},{"col":4,"comment":"Registers a function to be run before the first request to this\n instance of the application.\n\n The function will be called without any arguments and its return\n value is ignored.\n\n .. versionadded:: 0.8\n ","endLoc":1211,"header":"@setupmethod\n def before_first_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable","id":336,"name":"before_first_request","nodeType":"Function","startLoc":1200,"text":"@setupmethod\n def before_first_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:\n \"\"\"Registers a function to be run before the first request to this\n instance of the application.\n\n The function will be called without any arguments and its return\n value is ignored.\n\n .. versionadded:: 0.8\n \"\"\"\n self.before_first_request_funcs.append(f)\n return f"},{"id":337,"name":"tests/static","nodeType":"Package"},{"id":338,"name":"index.html","nodeType":"TextFile","path":"tests/static","text":"

Hello World!

\n"},{"id":339,"name":"tests/templates","nodeType":"Package"},{"id":340,"name":"context_template.html","nodeType":"TextFile","path":"tests/templates","text":"

{{ value }}|{{ injected_value }}\n"},{"col":4,"comment":"Checks if a given object is a null session. Null sessions are\n not asked to be saved.\n\n This checks if the object is an instance of :attr:`null_session_class`\n by default.\n ","endLoc":169,"header":"def is_null_session(self, obj: object) -> bool","id":341,"name":"is_null_session","nodeType":"Function","startLoc":162,"text":"def is_null_session(self, obj: object) -> bool:\n \"\"\"Checks if a given object is a null session. Null sessions are\n not asked to be saved.\n\n This checks if the object is an instance of :attr:`null_session_class`\n by default.\n \"\"\"\n return isinstance(obj, self.null_session_class)"},{"col":4,"comment":"Returns the name of the session cookie.\n\n Uses ``app.session_cookie_name`` which is set to ``SESSION_COOKIE_NAME``\n ","endLoc":176,"header":"def get_cookie_name(self, app: \"Flask\") -> str","id":342,"name":"get_cookie_name","nodeType":"Function","startLoc":171,"text":"def get_cookie_name(self, app: \"Flask\") -> str:\n \"\"\"Returns the name of the session cookie.\n\n Uses ``app.session_cookie_name`` which is set to ``SESSION_COOKIE_NAME``\n \"\"\"\n return app.session_cookie_name"},{"col":4,"comment":"Returns the domain that should be set for the session cookie.\n\n Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise\n falls back to detecting the domain based on ``SERVER_NAME``.\n\n Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is\n updated to avoid re-running the logic.\n ","endLoc":234,"header":"def get_cookie_domain(self, app: \"Flask\") -> t.Optional[str]","id":343,"name":"get_cookie_domain","nodeType":"Function","startLoc":178,"text":"def get_cookie_domain(self, app: \"Flask\") -> t.Optional[str]:\n \"\"\"Returns the domain that should be set for the session cookie.\n\n Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise\n falls back to detecting the domain based on ``SERVER_NAME``.\n\n Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is\n updated to avoid re-running the logic.\n \"\"\"\n\n rv = app.config[\"SESSION_COOKIE_DOMAIN\"]\n\n # set explicitly, or cached from SERVER_NAME detection\n # if False, return None\n if rv is not None:\n return rv if rv else None\n\n rv = app.config[\"SERVER_NAME\"]\n\n # server name not set, cache False to return none next time\n if not rv:\n app.config[\"SESSION_COOKIE_DOMAIN\"] = False\n return None\n\n # chop off the port which is usually not supported by browsers\n # remove any leading '.' since we'll add that later\n rv = rv.rsplit(\":\", 1)[0].lstrip(\".\")\n\n if \".\" not in rv:\n # Chrome doesn't allow names without a '.'. This should only\n # come up with localhost. Hack around this by not setting\n # the name, and show a warning.\n warnings.warn(\n f\"{rv!r} is not a valid cookie domain, it must contain\"\n \" a '.'. Add an entry to your hosts file, for example\"\n f\" '{rv}.localdomain', and use that instead.\"\n )\n app.config[\"SESSION_COOKIE_DOMAIN\"] = False\n return None\n\n ip = is_ip(rv)\n\n if ip:\n warnings.warn(\n \"The session cookie domain is an IP address. This may not work\"\n \" as intended in some browsers. Add an entry to your hosts\"\n ' file, for example \"localhost.localdomain\", and use that'\n \" instead.\"\n )\n\n # if this is not an ip and app is mounted at the root, allow subdomain\n # matching by adding a '.' prefix\n if self.get_cookie_path(app) == \"/\" and not ip:\n rv = f\".{rv}\"\n\n app.config[\"SESSION_COOKIE_DOMAIN\"] = rv\n return rv"},{"id":344,"name":"tests/test_apps/blueprintapp/apps/admin/static/css","nodeType":"Package"},{"id":345,"name":"test.css","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/admin/static/css","text":"/* nested file */\n"},{"id":346,"name":"tests.yaml","nodeType":"TextFile","path":".github/workflows","text":"name: Tests\non:\n push:\n branches:\n - main\n - '*.x'\n paths-ignore:\n - 'docs/**'\n - '*.md'\n - '*.rst'\n pull_request:\n branches:\n - main\n - '*.x'\n paths-ignore:\n - 'docs/**'\n - '*.md'\n - '*.rst'\njobs:\n tests:\n name: ${{ matrix.name }}\n runs-on: ${{ matrix.os }}\n strategy:\n fail-fast: false\n matrix:\n include:\n - {name: Linux, python: '3.9', os: ubuntu-latest, tox: py39}\n - {name: Windows, python: '3.9', os: windows-latest, tox: py39}\n - {name: Mac, python: '3.9', os: macos-latest, tox: py39}\n - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38}\n - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37}\n - {name: '3.6', python: '3.6', os: ubuntu-latest, tox: py36}\n - {name: 'PyPy', python: pypy3, os: ubuntu-latest, tox: pypy3}\n - {name: Typing, python: '3.9', os: ubuntu-latest, tox: typing}\n steps:\n - uses: actions/checkout@v2\n - uses: actions/setup-python@v2\n with:\n python-version: ${{ matrix.python }}\n - name: update pip\n run: |\n pip install -U wheel\n pip install -U setuptools\n python -m pip install -U pip\n - name: get pip cache dir\n id: pip-cache\n run: echo \"::set-output name=dir::$(pip cache dir)\"\n - name: cache pip\n uses: actions/cache@v2\n with:\n path: ${{ steps.pip-cache.outputs.dir }}\n key: pip|${{ runner.os }}|${{ matrix.python }}|${{ hashFiles('setup.py') }}|${{ hashFiles('requirements/*.txt') }}\n - run: pip install tox\n - run: tox -e ${{ matrix.tox }}\n"},{"id":347,"name":"next.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Keep Developing!\n================\n\nYou've learned about quite a few Flask and Python concepts throughout\nthe tutorial. Go back and review the tutorial and compare your code with\nthe steps you took to get there. Compare your project to the\n:gh:`example project `, which might look a bit\ndifferent due to the step-by-step nature of the tutorial.\n\nThere's a lot more to Flask than what you've seen so far. Even so,\nyou're now equipped to start developing your own web applications. Check\nout the :doc:`/quickstart` for an overview of what Flask can do, then\ndive into the docs to keep learning. Flask uses `Jinja`_, `Click`_,\n`Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have\ntheir own documentation too. You'll also be interested in\n:doc:`/extensions` which make tasks like working with the database or\nvalidating form data easier and more powerful.\n\nIf you want to keep developing your Flaskr project, here are some ideas\nfor what to try next:\n\n* A detail view to show a single post. Click a post's title to go to\n its page.\n* Like / unlike a post.\n* Comments.\n* Tags. Clicking a tag shows all the posts with that tag.\n* A search box that filters the index page by name.\n* Paged display. Only show 5 posts per page.\n* Upload an image to go along with a post.\n* Format posts using Markdown.\n* An RSS feed of new posts.\n\nHave fun and make awesome applications!\n\n.. _Jinja: https://palletsprojects.com/p/jinja/\n.. _Click: https://palletsprojects.com/p/click/\n.. _Werkzeug: https://palletsprojects.com/p/werkzeug/\n.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/\n"},{"fileName":"__init__.py","filePath":"src/flask","id":348,"nodeType":"File","text":"from markupsafe import escape\nfrom markupsafe import Markup\nfrom werkzeug.exceptions import abort as abort\nfrom werkzeug.utils import redirect as redirect\n\nfrom . import json as json\nfrom .app import Flask as Flask\nfrom .app import Request as Request\nfrom .app import Response as Response\nfrom .blueprints import Blueprint as Blueprint\nfrom .config import Config as Config\nfrom .ctx import after_this_request as after_this_request\nfrom .ctx import copy_current_request_context as copy_current_request_context\nfrom .ctx import has_app_context as has_app_context\nfrom .ctx import has_request_context as has_request_context\nfrom .globals import _app_ctx_stack as _app_ctx_stack\nfrom .globals import _request_ctx_stack as _request_ctx_stack\nfrom .globals import current_app as current_app\nfrom .globals import g as g\nfrom .globals import request as request\nfrom .globals import session as session\nfrom .helpers import flash as flash\nfrom .helpers import get_flashed_messages as get_flashed_messages\nfrom .helpers import get_template_attribute as get_template_attribute\nfrom .helpers import make_response as make_response\nfrom .helpers import safe_join as safe_join\nfrom .helpers import send_file as send_file\nfrom .helpers import send_from_directory as send_from_directory\nfrom .helpers import stream_with_context as stream_with_context\nfrom .helpers import url_for as url_for\nfrom .json import jsonify as jsonify\nfrom .signals import appcontext_popped as appcontext_popped\nfrom .signals import appcontext_pushed as appcontext_pushed\nfrom .signals import appcontext_tearing_down as appcontext_tearing_down\nfrom .signals import before_render_template as before_render_template\nfrom .signals import got_request_exception as got_request_exception\nfrom .signals import message_flashed as message_flashed\nfrom .signals import request_finished as request_finished\nfrom .signals import request_started as request_started\nfrom .signals import request_tearing_down as request_tearing_down\nfrom .signals import signals_available as signals_available\nfrom .signals import template_rendered as template_rendered\nfrom .templating import render_template as render_template\nfrom .templating import render_template_string as render_template_string\n\n__version__ = \"2.0.1.dev0\"\n"},{"col":4,"comment":"Registers a function to be called when the application context\n ends. These functions are typically also called when the request\n context is popped.\n\n Example::\n\n ctx = app.app_context()\n ctx.push()\n ...\n ctx.pop()\n\n When ``ctx.pop()`` is executed in the above example, the teardown\n functions are called just before the app context moves from the\n stack of active contexts. This becomes relevant if you are using\n such constructs in tests.\n\n Since a request context typically also manages an application\n context it would also be called when you pop a request context.\n\n When a teardown function was called because of an unhandled exception\n it will be passed an error object. If an :meth:`errorhandler` is\n registered, it will handle the exception and the teardown will not\n receive it.\n\n The return values of teardown functions are ignored.\n\n .. versionadded:: 0.9\n ","endLoc":1244,"header":"@setupmethod\n def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable","id":349,"name":"teardown_appcontext","nodeType":"Function","startLoc":1213,"text":"@setupmethod\n def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:\n \"\"\"Registers a function to be called when the application context\n ends. These functions are typically also called when the request\n context is popped.\n\n Example::\n\n ctx = app.app_context()\n ctx.push()\n ...\n ctx.pop()\n\n When ``ctx.pop()`` is executed in the above example, the teardown\n functions are called just before the app context moves from the\n stack of active contexts. This becomes relevant if you are using\n such constructs in tests.\n\n Since a request context typically also manages an application\n context it would also be called when you pop a request context.\n\n When a teardown function was called because of an unhandled exception\n it will be passed an error object. If an :meth:`errorhandler` is\n registered, it will handle the exception and the teardown will not\n receive it.\n\n The return values of teardown functions are ignored.\n\n .. versionadded:: 0.9\n \"\"\"\n self.teardown_appcontext_funcs.append(f)\n return f"},{"col":4,"comment":"Registers a shell context processor function.\n\n .. versionadded:: 0.11\n ","endLoc":1253,"header":"@setupmethod\n def shell_context_processor(self, f: t.Callable) -> t.Callable","id":350,"name":"shell_context_processor","nodeType":"Function","startLoc":1246,"text":"@setupmethod\n def shell_context_processor(self, f: t.Callable) -> t.Callable:\n \"\"\"Registers a shell context processor function.\n\n .. versionadded:: 0.11\n \"\"\"\n self.shell_context_processors.append(f)\n return f"},{"col":0,"comment":"Show extra startup messages the first time the server is run,\n ignoring the reloader.\n ","endLoc":689,"header":"def show_server_banner(env, debug, app_import_path, eager_loading)","id":351,"name":"show_server_banner","nodeType":"Function","startLoc":663,"text":"def show_server_banner(env, debug, app_import_path, eager_loading):\n \"\"\"Show extra startup messages the first time the server is run,\n ignoring the reloader.\n \"\"\"\n if os.environ.get(\"WERKZEUG_RUN_MAIN\") == \"true\":\n return\n\n if app_import_path is not None:\n message = f\" * Serving Flask app {app_import_path!r}\"\n\n if not eager_loading:\n message += \" (lazy loading)\"\n\n click.echo(message)\n\n click.echo(f\" * Environment: {env}\")\n\n if env == \"production\":\n click.secho(\n \" WARNING: This is a development server. Do not use it in\"\n \" a production deployment.\",\n fg=\"red\",\n )\n click.secho(\" Use a production WSGI server instead.\", dim=True)\n\n if debug is not None:\n click.echo(f\" * Debug mode: {'on' if debug else 'off'}\")"},{"className":"Blueprint","col":0,"comment":"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path: The url to serve static files from.\n Defaults to ``static_folder``. If the blueprint does not have\n a ``url_prefix``, the app's static route will take precedence,\n and the blueprint's static files won't be accessible.\n :param template_folder: A folder with templates that should be added\n to the app's template search path. The path is relative to the\n blueprint's root path. Blueprint templates are disabled by\n default. Blueprint templates have a lower precedence than those\n in the app's templates folder.\n :param url_prefix: A path to prepend to all of the blueprint's URLs,\n to make them distinct from the rest of the app's routes.\n :param subdomain: A subdomain that blueprint routes will match on by\n default.\n :param url_defaults: A dict of default values that blueprint routes\n will receive by default.\n :param root_path: By default, the blueprint will automatically set\n this based on ``import_name``. In certain situations this\n automatic detection can fail, so the path can be specified\n manually instead.\n\n .. versionchanged:: 1.1.0\n Blueprints have a ``cli`` group to register nested CLI commands.\n The ``cli_group`` parameter controls the name of the group under\n the ``flask`` command.\n\n .. versionadded:: 0.7\n ","endLoc":542,"id":352,"nodeType":"Class","startLoc":108,"text":"class Blueprint(Scaffold):\n \"\"\"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path: The url to serve static files from.\n Defaults to ``static_folder``. If the blueprint does not have\n a ``url_prefix``, the app's static route will take precedence,\n and the blueprint's static files won't be accessible.\n :param template_folder: A folder with templates that should be added\n to the app's template search path. The path is relative to the\n blueprint's root path. Blueprint templates are disabled by\n default. Blueprint templates have a lower precedence than those\n in the app's templates folder.\n :param url_prefix: A path to prepend to all of the blueprint's URLs,\n to make them distinct from the rest of the app's routes.\n :param subdomain: A subdomain that blueprint routes will match on by\n default.\n :param url_defaults: A dict of default values that blueprint routes\n will receive by default.\n :param root_path: By default, the blueprint will automatically set\n this based on ``import_name``. In certain situations this\n automatic detection can fail, so the path can be specified\n manually instead.\n\n .. versionchanged:: 1.1.0\n Blueprints have a ``cli`` group to register nested CLI commands.\n The ``cli_group`` parameter controls the name of the group under\n the ``flask`` command.\n\n .. versionadded:: 0.7\n \"\"\"\n\n warn_on_modifications = False\n _got_registered_once = False\n\n #: Blueprint local JSON encoder class to use. Set to ``None`` to use\n #: the app's :class:`~flask.Flask.json_encoder`.\n json_encoder = None\n #: Blueprint local JSON decoder class to use. Set to ``None`` to use\n #: the app's :class:`~flask.Flask.json_decoder`.\n json_decoder = None\n\n def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[str] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[str] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: t.List[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_group = cli_group\n self._blueprints: t.List[t.Tuple[\"Blueprint\", dict]] = []\n\n def _is_setup_finished(self) -> bool:\n return self.warn_on_modifications and self._got_registered_once\n\n def record(self, func: t.Callable) -> None:\n \"\"\"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n \"\"\"\n if self._got_registered_once and self.warn_on_modifications:\n from warnings import warn\n\n warn(\n Warning(\n \"The blueprint was already registered once but is\"\n \" getting modified now. These changes will not show\"\n \" up.\"\n )\n )\n self.deferred_functions.append(func)\n\n def record_once(self, func: t.Callable) -> None:\n \"\"\"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n \"\"\"\n\n def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)\n\n return self.record(update_wrapper(wrapper, func))\n\n def make_setup_state(\n self, app: \"Flask\", options: dict, first_registration: bool = False\n ) -> BlueprintSetupState:\n \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n \"\"\"\n return BlueprintSetupState(self, app, options, first_registration)\n\n def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionadded:: 2.0\n \"\"\"\n self._blueprints.append((blueprint, options))\n\n def register(self, app: \"Flask\", options: dict) -> None:\n \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n views and callbacks registered on the blueprint with the\n application. Creates a :class:`.BlueprintSetupState` and calls\n each :meth:`record` callbackwith it.\n\n :param app: The application this blueprint is being registered\n with.\n :param options: Keyword arguments forwarded from\n :meth:`~Flask.register_blueprint`.\n :param first_registration: Whether this is the first time this\n blueprint has been registered on the application.\n \"\"\"\n first_registration = False\n\n if self.name in app.blueprints:\n assert app.blueprints[self.name] is self, (\n \"A name collision occurred between blueprints\"\n f\" {self!r} and {app.blueprints[self.name]!r}.\"\n f\" Both share the same name {self.name!r}.\"\n f\" Blueprints that are created on the fly need unique\"\n f\" names.\"\n )\n else:\n app.blueprints[self.name] = self\n first_registration = True\n\n self._got_registered_once = True\n state = self.make_setup_state(app, options, first_registration)\n\n if self.has_static_folder:\n state.add_url_rule(\n f\"{self.static_url_path}/\",\n view_func=self.send_static_file,\n endpoint=\"static\",\n )\n\n # Merge blueprint data into parent.\n if first_registration:\n\n def extend(bp_dict, parent_dict):\n for key, values in bp_dict.items():\n key = self.name if key is None else f\"{self.name}.{key}\"\n\n parent_dict[key].extend(values)\n\n for key, value in self.error_handler_spec.items():\n key = self.name if key is None else f\"{self.name}.{key}\"\n value = defaultdict(\n dict,\n {\n code: {\n exc_class: func for exc_class, func in code_values.items()\n }\n for code, code_values in value.items()\n },\n )\n app.error_handler_spec[key] = value\n\n for endpoint, func in self.view_functions.items():\n app.view_functions[endpoint] = func\n\n extend(self.before_request_funcs, app.before_request_funcs)\n extend(self.after_request_funcs, app.after_request_funcs)\n extend(\n self.teardown_request_funcs,\n app.teardown_request_funcs,\n )\n extend(self.url_default_functions, app.url_default_functions)\n extend(self.url_value_preprocessors, app.url_value_preprocessors)\n extend(self.template_context_processors, app.template_context_processors)\n\n for deferred in self.deferred_functions:\n deferred(state)\n\n cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n if self.cli.commands:\n if cli_resolved_group is None:\n app.cli.commands.update(self.cli.commands)\n elif cli_resolved_group is _sentinel:\n self.cli.name = self.name\n app.cli.add_command(self.cli)\n else:\n self.cli.name = cli_resolved_group\n app.cli.add_command(self.cli)\n\n for blueprint, bp_options in self._blueprints:\n url_prefix = options.get(\"url_prefix\", \"\")\n if \"url_prefix\" in bp_options:\n url_prefix = (\n url_prefix.rstrip(\"/\") + \"/\" + bp_options[\"url_prefix\"].lstrip(\"/\")\n )\n\n bp_options[\"url_prefix\"] = url_prefix\n bp_options[\"name_prefix\"] = options.get(\"name_prefix\", \"\") + self.name + \".\"\n blueprint.register(app, bp_options)\n\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for\n the :func:`url_for` function is prefixed with the name of the blueprint.\n \"\"\"\n if endpoint:\n assert \".\" not in endpoint, \"Blueprint endpoints should not contain dots\"\n if view_func and hasattr(view_func, \"__name__\"):\n assert (\n \".\" not in view_func.__name__\n ), \"Blueprint view function name should not contain dots\"\n self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))\n\n def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template filter, available application wide. Like\n :meth:`Flask.template_filter` but for a blueprint.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:\n self.add_app_template_filter(f, name=name)\n return f\n\n return decorator\n\n def add_app_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template filter, available application wide. Like\n :meth:`Flask.add_template_filter` but for a blueprint. Works exactly\n like the :meth:`app_template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.filters[name or f.__name__] = f\n\n self.record_once(register_template)\n\n def app_template_test(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template test, available application wide. Like\n :meth:`Flask.template_test` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateTestCallable) -> TemplateTestCallable:\n self.add_app_template_test(f, name=name)\n return f\n\n return decorator\n\n def add_app_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template test, available application wide. Like\n :meth:`Flask.add_template_test` but for a blueprint. Works exactly\n like the :meth:`app_template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.tests[name or f.__name__] = f\n\n self.record_once(register_template)\n\n def app_template_global(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template global, available application wide. Like\n :meth:`Flask.template_global` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:\n self.add_app_template_global(f, name=name)\n return f\n\n return decorator\n\n def add_app_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template global, available application wide. Like\n :meth:`Flask.add_template_global` but for a blueprint. Works exactly\n like the :meth:`app_template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.globals[name or f.__name__] = f\n\n self.record_once(register_template)\n\n def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:\n \"\"\"Like :meth:`Flask.before_request`. Such a function is executed\n before each request, even if outside of a blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n def before_app_first_request(\n self, f: BeforeRequestCallable\n ) -> BeforeRequestCallable:\n \"\"\"Like :meth:`Flask.before_first_request`. Such a function is\n executed before the first request to the application.\n \"\"\"\n self.record_once(lambda s: s.app.before_first_request_funcs.append(f))\n return f\n\n def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:\n \"\"\"Like :meth:`Flask.after_request` but for a blueprint. Such a function\n is executed after each request, even if outside of the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:\n \"\"\"Like :meth:`Flask.teardown_request` but for a blueprint. Such a\n function is executed when tearing down each request, even if outside of\n the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n def app_context_processor(\n self, f: TemplateContextProcessorCallable\n ) -> TemplateContextProcessorCallable:\n \"\"\"Like :meth:`Flask.context_processor` but for a blueprint. Such a\n function is executed each request, even if outside of the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n )\n return f\n\n def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:\n \"\"\"Like :meth:`Flask.errorhandler` but for a blueprint. This\n handler is used for all requests, even if outside of the blueprint.\n \"\"\"\n\n def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:\n self.record_once(lambda s: s.app.errorhandler(code)(f))\n return f\n\n return decorator\n\n def app_url_value_preprocessor(\n self, f: URLValuePreprocessorCallable\n ) -> URLValuePreprocessorCallable:\n \"\"\"Same as :meth:`url_value_preprocessor` but application wide.\"\"\"\n self.record_once(\n lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n )\n return f\n\n def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:\n \"\"\"Same as :meth:`url_defaults` but application wide.\"\"\"\n self.record_once(\n lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n )\n return f"},{"col":4,"comment":"Return a registered error handler for an exception in this order:\n blueprint handler for a specific code, app handler for a specific code,\n blueprint handler for an exception class, app handler for an exception\n class, or ``None`` if a suitable handler is not found.\n ","endLoc":1275,"header":"def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]","id":353,"name":"_find_error_handler","nodeType":"Function","startLoc":1255,"text":"def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:\n \"\"\"Return a registered error handler for an exception in this order:\n blueprint handler for a specific code, app handler for a specific code,\n blueprint handler for an exception class, app handler for an exception\n class, or ``None`` if a suitable handler is not found.\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(type(e))\n\n for c in [code, None]:\n for name in chain(self._request_blueprints(), [None]):\n handler_map = self.error_handler_spec[name][c]\n\n if not handler_map:\n continue\n\n for cls in exc_class.__mro__:\n handler = handler_map.get(cls)\n\n if handler is not None:\n return handler\n return None"},{"col":4,"comment":"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n ","endLoc":244,"header":"def make_setup_state(\n self, app: \"Flask\", options: dict, first_registration: bool = False\n ) -> BlueprintSetupState","id":354,"name":"make_setup_state","nodeType":"Function","startLoc":237,"text":"def make_setup_state(\n self, app: \"Flask\", options: dict, first_registration: bool = False\n ) -> BlueprintSetupState:\n \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n \"\"\"\n return BlueprintSetupState(self, app, options, first_registration)"},{"col":4,"comment":"Handles an HTTP exception. By default this will invoke the\n registered error handlers and fall back to returning the\n exception as response.\n\n .. versionchanged:: 1.0.3\n ``RoutingException``, used internally for actions such as\n slash redirects during routing, is not passed to error\n handlers.\n\n .. versionchanged:: 1.0\n Exceptions are looked up by code *and* by MRO, so\n ``HTTPExcpetion`` subclasses can be handled with a catch-all\n handler for the base ``HTTPException``.\n\n .. versionadded:: 0.3\n ","endLoc":1310,"header":"def handle_http_exception(\n self, e: HTTPException\n ) -> t.Union[HTTPException, ResponseReturnValue]","id":355,"name":"handle_http_exception","nodeType":"Function","startLoc":1277,"text":"def handle_http_exception(\n self, e: HTTPException\n ) -> t.Union[HTTPException, ResponseReturnValue]:\n \"\"\"Handles an HTTP exception. By default this will invoke the\n registered error handlers and fall back to returning the\n exception as response.\n\n .. versionchanged:: 1.0.3\n ``RoutingException``, used internally for actions such as\n slash redirects during routing, is not passed to error\n handlers.\n\n .. versionchanged:: 1.0\n Exceptions are looked up by code *and* by MRO, so\n ``HTTPExcpetion`` subclasses can be handled with a catch-all\n handler for the base ``HTTPException``.\n\n .. versionadded:: 0.3\n \"\"\"\n # Proxy exceptions don't have error codes. We want to always return\n # those unchanged as errors\n if e.code is None:\n return e\n\n # RoutingExceptions are used internally to trigger routing\n # actions, such as slash redirects raising RequestRedirect. They\n # are not raised or handled in user code.\n if isinstance(e, RoutingException):\n return e\n\n handler = self._find_error_handler(e)\n if handler is None:\n return e\n return self.ensure_sync(handler)(e)"},{"col":4,"comment":"null","endLoc":201,"header":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[str] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[str] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n )","id":356,"name":"__init__","nodeType":"Function","startLoc":171,"text":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[str] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[str] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: t.List[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_group = cli_group\n self._blueprints: t.List[t.Tuple[\"Blueprint\", dict]] = []"},{"col":4,"comment":"Ensure that the function is synchronous for WSGI workers.\n Plain ``def`` functions are returned as-is. ``async def``\n functions are wrapped to run and wait for the response.\n\n Override this method to change how the app runs async views.\n\n .. versionadded:: 2.0\n ","endLoc":1585,"header":"def ensure_sync(self, func: t.Callable) -> t.Callable","id":357,"name":"ensure_sync","nodeType":"Function","startLoc":1573,"text":"def ensure_sync(self, func: t.Callable) -> t.Callable:\n \"\"\"Ensure that the function is synchronous for WSGI workers.\n Plain ``def`` functions are returned as-is. ``async def``\n functions are wrapped to run and wait for the response.\n\n Override this method to change how the app runs async views.\n\n .. versionadded:: 2.0\n \"\"\"\n if iscoroutinefunction(func):\n return self.async_to_sync(func)\n\n return func"},{"col":4,"comment":"Checks if an HTTP exception should be trapped or not. By default\n this will return ``False`` for all exceptions except for a bad request\n key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It\n also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.\n\n This is called for all HTTP exceptions raised by a view function.\n If it returns ``True`` for any exception the error handler for this\n exception is not called and it shows up as regular exception in the\n traceback. This is helpful for debugging implicitly raised HTTP\n exceptions.\n\n .. versionchanged:: 1.0\n Bad request errors are not trapped by default in debug mode.\n\n .. versionadded:: 0.8\n ","endLoc":1345,"header":"def trap_http_exception(self, e: Exception) -> bool","id":358,"name":"trap_http_exception","nodeType":"Function","startLoc":1312,"text":"def trap_http_exception(self, e: Exception) -> bool:\n \"\"\"Checks if an HTTP exception should be trapped or not. By default\n this will return ``False`` for all exceptions except for a bad request\n key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It\n also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.\n\n This is called for all HTTP exceptions raised by a view function.\n If it returns ``True`` for any exception the error handler for this\n exception is not called and it shows up as regular exception in the\n traceback. This is helpful for debugging implicitly raised HTTP\n exceptions.\n\n .. versionchanged:: 1.0\n Bad request errors are not trapped by default in debug mode.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.config[\"TRAP_HTTP_EXCEPTIONS\"]:\n return True\n\n trap_bad_request = self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n\n # if unset, trap key errors in debug mode\n if (\n trap_bad_request is None\n and self.debug\n and isinstance(e, BadRequestKeyError)\n ):\n return True\n\n if trap_bad_request:\n return isinstance(e, BadRequest)\n\n return False"},{"col":4,"comment":"null","endLoc":91,"header":"def iscoroutinefunction(func: t.Any) -> bool","id":359,"name":"iscoroutinefunction","nodeType":"Function","startLoc":84,"text":"def iscoroutinefunction(func: t.Any) -> bool:\n while inspect.ismethod(func):\n func = func.__func__\n\n while isinstance(func, functools.partial):\n func = func.func\n\n return inspect.iscoroutinefunction(func)"},{"col":4,"comment":"This method is called whenever an exception occurs that\n should be handled. A special case is :class:`~werkzeug\n .exceptions.HTTPException` which is forwarded to the\n :meth:`handle_http_exception` method. This function will either\n return a response value or reraise the exception with the same\n traceback.\n\n .. versionchanged:: 1.0\n Key errors raised from request data like ``form`` show the\n bad key in debug mode rather than a generic bad request\n message.\n\n .. versionadded:: 0.7\n ","endLoc":1377,"header":"def handle_user_exception(\n self, e: Exception\n ) -> t.Union[HTTPException, ResponseReturnValue]","id":360,"name":"handle_user_exception","nodeType":"Function","startLoc":1347,"text":"def handle_user_exception(\n self, e: Exception\n ) -> t.Union[HTTPException, ResponseReturnValue]:\n \"\"\"This method is called whenever an exception occurs that\n should be handled. A special case is :class:`~werkzeug\n .exceptions.HTTPException` which is forwarded to the\n :meth:`handle_http_exception` method. This function will either\n return a response value or reraise the exception with the same\n traceback.\n\n .. versionchanged:: 1.0\n Key errors raised from request data like ``form`` show the\n bad key in debug mode rather than a generic bad request\n message.\n\n .. versionadded:: 0.7\n \"\"\"\n if isinstance(e, BadRequestKeyError) and (\n self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n ):\n e.show_exception = True\n\n if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n return self.handle_http_exception(e)\n\n handler = self._find_error_handler(e)\n\n if handler is None:\n raise\n\n return self.ensure_sync(handler)(e)"},{"col":4,"comment":"null","endLoc":75,"header":"def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None","id":361,"name":"__init__","nodeType":"Function","startLoc":32,"text":"def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_prefix\n #: The prefix that should be used for all URLs defined on the\n #: blueprint.\n self.url_prefix = url_prefix\n\n self.name_prefix = self.options.get(\"name_prefix\", \"\")\n\n #: A dictionary with URL defaults that is added to each and every\n #: URL that was defined with the blueprint.\n self.url_defaults = dict(self.blueprint.url_values_defaults)\n self.url_defaults.update(self.options.get(\"url_defaults\", ()))"},{"col":4,"comment":"Return a sync function that will run the coroutine function.\n\n .. code-block:: python\n\n result = app.async_to_sync(func)(*args, **kwargs)\n\n Override this method to change how the app converts async code\n to be synchronously callable.\n\n .. versionadded:: 2.0\n ","endLoc":1615,"header":"def async_to_sync(\n self, func: t.Callable[..., t.Coroutine]\n ) -> t.Callable[..., t.Any]","id":362,"name":"async_to_sync","nodeType":"Function","startLoc":1587,"text":"def async_to_sync(\n self, func: t.Callable[..., t.Coroutine]\n ) -> t.Callable[..., t.Any]:\n \"\"\"Return a sync function that will run the coroutine function.\n\n .. code-block:: python\n\n result = app.async_to_sync(func)(*args, **kwargs)\n\n Override this method to change how the app converts async code\n to be synchronously callable.\n\n .. versionadded:: 2.0\n \"\"\"\n try:\n from asgiref.sync import async_to_sync as asgiref_async_to_sync\n except ImportError:\n raise RuntimeError(\n \"Install Flask with the 'async' extra in order to use async views.\"\n )\n\n # Check that Werkzeug isn't using its fallback ContextVar class.\n if ContextVar.__module__ == \"werkzeug.local\":\n raise RuntimeError(\n \"Async cannot be used with this combination of Python \"\n \"and Greenlet versions.\"\n )\n\n return asgiref_async_to_sync(func)"},{"col":4,"comment":"Handle an exception that did not have an error handler\n associated with it, or that was raised from an error handler.\n This always causes a 500 ``InternalServerError``.\n\n Always sends the :data:`got_request_exception` signal.\n\n If :attr:`propagate_exceptions` is ``True``, such as in debug\n mode, the error will be re-raised so that the debugger can\n display it. Otherwise, the original exception is logged, and\n an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n If an error handler is registered for ``InternalServerError`` or\n ``500``, it will be used. For consistency, the handler will\n always receive the ``InternalServerError``. The original\n unhandled exception is available as ``e.original_exception``.\n\n .. versionchanged:: 1.1.0\n Always passes the ``InternalServerError`` instance to the\n handler, setting ``original_exception`` to the unhandled\n error.\n\n .. versionchanged:: 1.1.0\n ``after_request`` functions and other finalization is done\n even for the default 500 response when there is no handler.\n\n .. versionadded:: 0.3\n ","endLoc":1426,"header":"def handle_exception(self, e: Exception) -> Response","id":363,"name":"handle_exception","nodeType":"Function","startLoc":1379,"text":"def handle_exception(self, e: Exception) -> Response:\n \"\"\"Handle an exception that did not have an error handler\n associated with it, or that was raised from an error handler.\n This always causes a 500 ``InternalServerError``.\n\n Always sends the :data:`got_request_exception` signal.\n\n If :attr:`propagate_exceptions` is ``True``, such as in debug\n mode, the error will be re-raised so that the debugger can\n display it. Otherwise, the original exception is logged, and\n an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n If an error handler is registered for ``InternalServerError`` or\n ``500``, it will be used. For consistency, the handler will\n always receive the ``InternalServerError``. The original\n unhandled exception is available as ``e.original_exception``.\n\n .. versionchanged:: 1.1.0\n Always passes the ``InternalServerError`` instance to the\n handler, setting ``original_exception`` to the unhandled\n error.\n\n .. versionchanged:: 1.1.0\n ``after_request`` functions and other finalization is done\n even for the default 500 response when there is no handler.\n\n .. versionadded:: 0.3\n \"\"\"\n exc_info = sys.exc_info()\n got_request_exception.send(self, exception=e)\n\n if self.propagate_exceptions:\n # Re-raise if called with an active exception, otherwise\n # raise the passed in exception.\n if exc_info[1] is e:\n raise\n\n raise e\n\n self.log_exception(exc_info)\n server_error: t.Union[InternalServerError, ResponseReturnValue]\n server_error = InternalServerError(original_exception=e)\n handler = self._find_error_handler(server_error)\n\n if handler is not None:\n server_error = self.ensure_sync(handler)(server_error)\n\n return self.finalize_request(server_error, from_error_handler=True)"},{"col":4,"comment":"null","endLoc":204,"header":"def _is_setup_finished(self) -> bool","id":364,"name":"_is_setup_finished","nodeType":"Function","startLoc":203,"text":"def _is_setup_finished(self) -> bool:\n return self.warn_on_modifications and self._got_registered_once"},{"col":4,"comment":"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n ","endLoc":222,"header":"def record(self, func: t.Callable) -> None","id":365,"name":"record","nodeType":"Function","startLoc":206,"text":"def record(self, func: t.Callable) -> None:\n \"\"\"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n \"\"\"\n if self._got_registered_once and self.warn_on_modifications:\n from warnings import warn\n\n warn(\n Warning(\n \"The blueprint was already registered once but is\"\n \" getting modified now. These changes will not show\"\n \" up.\"\n )\n )\n self.deferred_functions.append(func)"},{"col":4,"comment":"Returns the path for which the cookie should be valid. The\n default implementation uses the value from the ``SESSION_COOKIE_PATH``\n config var if it's set, and falls back to ``APPLICATION_ROOT`` or\n uses ``/`` if it's ``None``.\n ","endLoc":242,"header":"def get_cookie_path(self, app: \"Flask\") -> str","id":366,"name":"get_cookie_path","nodeType":"Function","startLoc":236,"text":"def get_cookie_path(self, app: \"Flask\") -> str:\n \"\"\"Returns the path for which the cookie should be valid. The\n default implementation uses the value from the ``SESSION_COOKIE_PATH``\n config var if it's set, and falls back to ``APPLICATION_ROOT`` or\n uses ``/`` if it's ``None``.\n \"\"\"\n return app.config[\"SESSION_COOKIE_PATH\"] or app.config[\"APPLICATION_ROOT\"]"},{"col":4,"comment":"Returns True if the session cookie should be httponly. This\n currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``\n config var.\n ","endLoc":249,"header":"def get_cookie_httponly(self, app: \"Flask\") -> bool","id":367,"name":"get_cookie_httponly","nodeType":"Function","startLoc":244,"text":"def get_cookie_httponly(self, app: \"Flask\") -> bool:\n \"\"\"Returns True if the session cookie should be httponly. This\n currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``\n config var.\n \"\"\"\n return app.config[\"SESSION_COOKIE_HTTPONLY\"]"},{"col":4,"comment":"Returns True if the cookie should be secure. This currently\n just returns the value of the ``SESSION_COOKIE_SECURE`` setting.\n ","endLoc":255,"header":"def get_cookie_secure(self, app: \"Flask\") -> bool","id":368,"name":"get_cookie_secure","nodeType":"Function","startLoc":251,"text":"def get_cookie_secure(self, app: \"Flask\") -> bool:\n \"\"\"Returns True if the cookie should be secure. This currently\n just returns the value of the ``SESSION_COOKIE_SECURE`` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SECURE\"]"},{"col":4,"comment":"Return ``'Strict'`` or ``'Lax'`` if the cookie should use the\n ``SameSite`` attribute. This currently just returns the value of\n the :data:`SESSION_COOKIE_SAMESITE` setting.\n ","endLoc":262,"header":"def get_cookie_samesite(self, app: \"Flask\") -> str","id":369,"name":"get_cookie_samesite","nodeType":"Function","startLoc":257,"text":"def get_cookie_samesite(self, app: \"Flask\") -> str:\n \"\"\"Return ``'Strict'`` or ``'Lax'`` if the cookie should use the\n ``SameSite`` attribute. This currently just returns the value of\n the :data:`SESSION_COOKIE_SAMESITE` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SAMESITE\"]"},{"col":4,"comment":"A helper method that returns an expiration date for the session\n or ``None`` if the session is linked to the browser session. The\n default implementation returns now + the permanent session\n lifetime configured on the application.\n ","endLoc":274,"header":"def get_expiration_time(\n self, app: \"Flask\", session: SessionMixin\n ) -> t.Optional[datetime]","id":370,"name":"get_expiration_time","nodeType":"Function","startLoc":264,"text":"def get_expiration_time(\n self, app: \"Flask\", session: SessionMixin\n ) -> t.Optional[datetime]:\n \"\"\"A helper method that returns an expiration date for the session\n or ``None`` if the session is linked to the browser session. The\n default implementation returns now + the permanent session\n lifetime configured on the application.\n \"\"\"\n if session.permanent:\n return datetime.utcnow() + app.permanent_session_lifetime\n return None"},{"col":4,"comment":"Logs an exception. This is called by :meth:`handle_exception`\n if debugging is disabled and right before the handler is called.\n The default implementation logs the exception as error on the\n :attr:`logger`.\n\n .. versionadded:: 0.8\n ","endLoc":1443,"header":"def log_exception(\n self,\n exc_info: t.Union[\n t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]\n ],\n ) -> None","id":371,"name":"log_exception","nodeType":"Function","startLoc":1428,"text":"def log_exception(\n self,\n exc_info: t.Union[\n t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]\n ],\n ) -> None:\n \"\"\"Logs an exception. This is called by :meth:`handle_exception`\n if debugging is disabled and right before the handler is called.\n The default implementation logs the exception as error on the\n :attr:`logger`.\n\n .. versionadded:: 0.8\n \"\"\"\n self.logger.error(\n f\"Exception on {request.path} [{request.method}]\", exc_info=exc_info\n )"},{"col":4,"comment":"Exceptions that are recording during routing are reraised with\n this method. During debug we are not reraising redirect requests\n for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising\n a different error instead to help debug situations.\n\n :internal:\n ","endLoc":1462,"header":"def raise_routing_exception(self, request: Request) -> \"te.NoReturn\"","id":372,"name":"raise_routing_exception","nodeType":"Function","startLoc":1445,"text":"def raise_routing_exception(self, request: Request) -> \"te.NoReturn\":\n \"\"\"Exceptions that are recording during routing are reraised with\n this method. During debug we are not reraising redirect requests\n for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising\n a different error instead to help debug situations.\n\n :internal:\n \"\"\"\n if (\n not self.debug\n or not isinstance(request.routing_exception, RequestRedirect)\n or request.method in (\"GET\", \"HEAD\", \"OPTIONS\")\n ):\n raise request.routing_exception # type: ignore\n\n from .debughelpers import FormDataRoutingRedirect\n\n raise FormDataRoutingRedirect(request)"},{"col":4,"comment":"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n ","endLoc":235,"header":"def record_once(self, func: t.Callable) -> None","id":373,"name":"record_once","nodeType":"Function","startLoc":224,"text":"def record_once(self, func: t.Callable) -> None:\n \"\"\"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n \"\"\"\n\n def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)\n\n return self.record(update_wrapper(wrapper, func))"},{"col":4,"comment":"null","endLoc":72,"header":"def __init__(self, request)","id":374,"name":"__init__","nodeType":"Function","startLoc":49,"text":"def __init__(self, request):\n exc = request.routing_exception\n buf = [\n f\"A request was sent to this URL ({request.url}) but a\"\n \" redirect was issued automatically by the routing system\"\n f\" to {exc.new_url!r}.\"\n ]\n\n # In case just a slash was appended we can be extra helpful\n if f\"{request.base_url}/\" == exc.new_url.split(\"?\")[0]:\n buf.append(\n \" The URL was defined with a trailing slash so Flask\"\n \" will automatically redirect to the URL with the\"\n \" trailing slash if it was accessed without one.\"\n )\n\n buf.append(\n \" Make sure to directly send your\"\n f\" {request.method}-request to this URL since we can't make\"\n \" browsers or HTTP clients redirect with form data reliably\"\n \" or without user interaction.\"\n )\n buf.append(\"\\n\\nNote: this exception is only raised in debug mode\")\n AssertionError.__init__(self, \"\".join(buf).encode(\"utf-8\"))"},{"col":4,"comment":"Does the request dispatching. Matches the URL and returns the\n return value of the view or error handler. This does not have to\n be a response object. In order to convert the return value to a\n proper response object, call :func:`make_response`.\n\n .. versionchanged:: 0.7\n This no longer does the exception handling, this code was\n moved to the new :meth:`full_dispatch_request`.\n ","endLoc":1486,"header":"def dispatch_request(self) -> ResponseReturnValue","id":375,"name":"dispatch_request","nodeType":"Function","startLoc":1464,"text":"def dispatch_request(self) -> ResponseReturnValue:\n \"\"\"Does the request dispatching. Matches the URL and returns the\n return value of the view or error handler. This does not have to\n be a response object. In order to convert the return value to a\n proper response object, call :func:`make_response`.\n\n .. versionchanged:: 0.7\n This no longer does the exception handling, this code was\n moved to the new :meth:`full_dispatch_request`.\n \"\"\"\n req = _request_ctx_stack.top.request\n if req.routing_exception is not None:\n self.raise_routing_exception(req)\n rule = req.url_rule\n # if we provide automatic options for this URL and the\n # request came with the OPTIONS method, reply automatically\n if (\n getattr(rule, \"provide_automatic_options\", False)\n and req.method == \"OPTIONS\"\n ):\n return self.make_default_options_response()\n # otherwise dispatch to the handler for that endpoint\n return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)"},{"col":4,"comment":"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionadded:: 2.0\n ","endLoc":253,"header":"def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None","id":376,"name":"register_blueprint","nodeType":"Function","startLoc":246,"text":"def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionadded:: 2.0\n \"\"\"\n self._blueprints.append((blueprint, options))"},{"col":4,"comment":"Dispatches the request and on top of that performs request\n pre and postprocessing as well as HTTP exception catching and\n error handling.\n\n .. versionadded:: 0.7\n ","endLoc":1503,"header":"def full_dispatch_request(self) -> Response","id":377,"name":"full_dispatch_request","nodeType":"Function","startLoc":1488,"text":"def full_dispatch_request(self) -> Response:\n \"\"\"Dispatches the request and on top of that performs request\n pre and postprocessing as well as HTTP exception catching and\n error handling.\n\n .. versionadded:: 0.7\n \"\"\"\n self.try_trigger_before_first_request_functions()\n try:\n request_started.send(self)\n rv = self.preprocess_request()\n if rv is None:\n rv = self.dispatch_request()\n except Exception as e:\n rv = self.handle_user_exception(e)\n return self.finalize_request(rv)"},{"col":4,"comment":"Used by session backends to determine if a ``Set-Cookie`` header\n should be set for this session cookie for this response. If the session\n has been modified, the cookie is set. If the session is permanent and\n the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is\n always set.\n\n This check is usually skipped if the session was deleted.\n\n .. versionadded:: 0.11\n ","endLoc":290,"header":"def should_set_cookie(self, app: \"Flask\", session: SessionMixin) -> bool","id":378,"name":"should_set_cookie","nodeType":"Function","startLoc":276,"text":"def should_set_cookie(self, app: \"Flask\", session: SessionMixin) -> bool:\n \"\"\"Used by session backends to determine if a ``Set-Cookie`` header\n should be set for this session cookie for this response. If the session\n has been modified, the cookie is set. If the session is permanent and\n the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is\n always set.\n\n This check is usually skipped if the session was deleted.\n\n .. versionadded:: 0.11\n \"\"\"\n\n return session.modified or (\n session.permanent and app.config[\"SESSION_REFRESH_EACH_REQUEST\"]\n )"},{"col":4,"comment":"This method has to be implemented and must either return ``None``\n in case the loading failed because of a configuration error or an\n instance of a session object which implements a dictionary like\n interface + the methods and attributes on :class:`SessionMixin`.\n ","endLoc":300,"header":"def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SessionMixin]","id":379,"name":"open_session","nodeType":"Function","startLoc":292,"text":"def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SessionMixin]:\n \"\"\"This method has to be implemented and must either return ``None``\n in case the loading failed because of a configuration error or an\n instance of a session object which implements a dictionary like\n interface + the methods and attributes on :class:`SessionMixin`.\n \"\"\"\n raise NotImplementedError()"},{"col":4,"comment":"Called before each request and will ensure that it triggers\n the :attr:`before_first_request_funcs` and only exactly once per\n application instance (which means process usually).\n\n :internal:\n ","endLoc":1548,"header":"def try_trigger_before_first_request_functions(self) -> None","id":380,"name":"try_trigger_before_first_request_functions","nodeType":"Function","startLoc":1534,"text":"def try_trigger_before_first_request_functions(self) -> None:\n \"\"\"Called before each request and will ensure that it triggers\n the :attr:`before_first_request_funcs` and only exactly once per\n application instance (which means process usually).\n\n :internal:\n \"\"\"\n if self._got_first_request:\n return\n with self._before_request_lock:\n if self._got_first_request:\n return\n for func in self.before_first_request_funcs:\n self.ensure_sync(func)()\n self._got_first_request = True"},{"col":4,"comment":"Given the return value from a view function this finalizes\n the request by converting it into a response and invoking the\n postprocessing functions. This is invoked for both normal\n request dispatching as well as error handlers.\n\n Because this means that it might be called as a result of a\n failure a special safe mode is available which can be enabled\n with the `from_error_handler` flag. If enabled, failures in\n response processing will be logged and otherwise ignored.\n\n :internal:\n ","endLoc":1532,"header":"def finalize_request(\n self,\n rv: t.Union[ResponseReturnValue, HTTPException],\n from_error_handler: bool = False,\n ) -> Response","id":381,"name":"finalize_request","nodeType":"Function","startLoc":1505,"text":"def finalize_request(\n self,\n rv: t.Union[ResponseReturnValue, HTTPException],\n from_error_handler: bool = False,\n ) -> Response:\n \"\"\"Given the return value from a view function this finalizes\n the request by converting it into a response and invoking the\n postprocessing functions. This is invoked for both normal\n request dispatching as well as error handlers.\n\n Because this means that it might be called as a result of a\n failure a special safe mode is available which can be enabled\n with the `from_error_handler` flag. If enabled, failures in\n response processing will be logged and otherwise ignored.\n\n :internal:\n \"\"\"\n response = self.make_response(rv)\n try:\n response = self.process_response(response)\n request_finished.send(self, response=response)\n except Exception:\n if not from_error_handler:\n raise\n self.logger.exception(\n \"Request finalizing failed with an error while handling an error\"\n )\n return response"},{"col":4,"comment":"This is called for actual sessions returned by :meth:`open_session`\n at the end of the request. This is still called during a request\n context so if you absolutely need access to the request you can do\n that.\n ","endLoc":310,"header":"def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None","id":382,"name":"save_session","nodeType":"Function","startLoc":302,"text":"def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None:\n \"\"\"This is called for actual sessions returned by :meth:`open_session`\n at the end of the request. This is still called during a request\n context so if you absolutely need access to the request you can do\n that.\n \"\"\"\n raise NotImplementedError()"},{"attributeType":"NullSession","col":4,"comment":"null","endLoc":141,"id":383,"name":"null_session_class","nodeType":"Attribute","startLoc":141,"text":"null_session_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":148,"id":384,"name":"pickle_based","nodeType":"Attribute","startLoc":148,"text":"pickle_based"},{"className":"SecureCookieSessionInterface","col":0,"comment":"The default session interface that stores sessions in signed cookies\n through the :mod:`itsdangerous` module.\n ","endLoc":404,"id":385,"nodeType":"Class","startLoc":316,"text":"class SecureCookieSessionInterface(SessionInterface):\n \"\"\"The default session interface that stores sessions in signed cookies\n through the :mod:`itsdangerous` module.\n \"\"\"\n\n #: the salt that should be applied on top of the secret key for the\n #: signing of cookie based sessions.\n salt = \"cookie-session\"\n #: the hash function to use for the signature. The default is sha1\n digest_method = staticmethod(hashlib.sha1)\n #: the name of the itsdangerous supported key derivation. The default\n #: is hmac.\n key_derivation = \"hmac\"\n #: A python serializer for the payload. The default is a compact\n #: JSON derived serializer with support for some extra Python types\n #: such as datetime objects or tuples.\n serializer = session_json_serializer\n session_class = SecureCookieSession\n\n def get_signing_serializer(\n self, app: \"Flask\"\n ) -> t.Optional[URLSafeTimedSerializer]:\n if not app.secret_key:\n return None\n signer_kwargs = dict(\n key_derivation=self.key_derivation, digest_method=self.digest_method\n )\n return URLSafeTimedSerializer(\n app.secret_key,\n salt=self.salt,\n serializer=self.serializer,\n signer_kwargs=signer_kwargs,\n )\n\n def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SecureCookieSession]:\n s = self.get_signing_serializer(app)\n if s is None:\n return None\n val = request.cookies.get(self.get_cookie_name(app))\n if not val:\n return self.session_class()\n max_age = int(app.permanent_session_lifetime.total_seconds())\n try:\n data = s.loads(val, max_age=max_age)\n return self.session_class(data)\n except BadSignature:\n return self.session_class()\n\n def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None:\n name = self.get_cookie_name(app)\n domain = self.get_cookie_domain(app)\n path = self.get_cookie_path(app)\n secure = self.get_cookie_secure(app)\n samesite = self.get_cookie_samesite(app)\n\n # If the session is modified to be empty, remove the cookie.\n # If the session is empty, return without setting the cookie.\n if not session:\n if session.modified:\n response.delete_cookie(\n name, domain=domain, path=path, secure=secure, samesite=samesite\n )\n\n return\n\n # Add a \"Vary: Cookie\" header if the session was accessed at all.\n if session.accessed:\n response.vary.add(\"Cookie\")\n\n if not self.should_set_cookie(app, session):\n return\n\n httponly = self.get_cookie_httponly(app)\n expires = self.get_expiration_time(app, session)\n val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore\n response.set_cookie(\n name,\n val, # type: ignore\n expires=expires,\n httponly=httponly,\n domain=domain,\n path=path,\n secure=secure,\n samesite=samesite,\n )"},{"col":4,"comment":"null","endLoc":348,"header":"def get_signing_serializer(\n self, app: \"Flask\"\n ) -> t.Optional[URLSafeTimedSerializer]","id":386,"name":"get_signing_serializer","nodeType":"Function","startLoc":335,"text":"def get_signing_serializer(\n self, app: \"Flask\"\n ) -> t.Optional[URLSafeTimedSerializer]:\n if not app.secret_key:\n return None\n signer_kwargs = dict(\n key_derivation=self.key_derivation, digest_method=self.digest_method\n )\n return URLSafeTimedSerializer(\n app.secret_key,\n salt=self.salt,\n serializer=self.serializer,\n signer_kwargs=signer_kwargs,\n )"},{"col":4,"comment":"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n A dictionary that will be jsonify'd before being returned.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n ``headers`` is a dictionary or a list of ``(key, value)``\n tuples. If ``body`` is a :attr:`response_class` instance,\n ``status`` overwrites the exiting value and ``headers`` are\n extended.\n\n :attr:`response_class`\n The object is returned unchanged.\n\n other :class:`~werkzeug.wrappers.Response` class\n The object is coerced to :attr:`response_class`.\n\n :func:`callable`\n The function is called as a WSGI application. The result is\n used to create a response object.\n\n .. versionchanged:: 0.9\n Previously a tuple was interpreted as the arguments for the\n response object.\n ","endLoc":1733,"header":"def make_response(self, rv: ResponseReturnValue) -> Response","id":387,"name":"make_response","nodeType":"Function","startLoc":1617,"text":"def make_response(self, rv: ResponseReturnValue) -> Response:\n \"\"\"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n A dictionary that will be jsonify'd before being returned.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n ``headers`` is a dictionary or a list of ``(key, value)``\n tuples. If ``body`` is a :attr:`response_class` instance,\n ``status`` overwrites the exiting value and ``headers`` are\n extended.\n\n :attr:`response_class`\n The object is returned unchanged.\n\n other :class:`~werkzeug.wrappers.Response` class\n The object is coerced to :attr:`response_class`.\n\n :func:`callable`\n The function is called as a WSGI application. The result is\n used to create a response object.\n\n .. versionchanged:: 0.9\n Previously a tuple was interpreted as the arguments for the\n response object.\n \"\"\"\n\n status = headers = None\n\n # unpack tuple returns\n if isinstance(rv, tuple):\n len_rv = len(rv)\n\n # a 3-tuple is unpacked directly\n if len_rv == 3:\n rv, status, headers = rv\n # decide if a 2-tuple has status or headers\n elif len_rv == 2:\n if isinstance(rv[1], (Headers, dict, tuple, list)):\n rv, headers = rv\n else:\n rv, status = rv\n # other sized tuples are not allowed\n else:\n raise TypeError(\n \"The view function did not return a valid response tuple.\"\n \" The tuple must have the form (body, status, headers),\"\n \" (body, status), or (body, headers).\"\n )\n\n # the body must not be None\n if rv is None:\n raise TypeError(\n f\"The view function for {request.endpoint!r} did not\"\n \" return a valid response. The function either returned\"\n \" None or ended without a return statement.\"\n )\n\n # make sure the body is an instance of the response class\n if not isinstance(rv, self.response_class):\n if isinstance(rv, (str, bytes, bytearray)):\n # let the response class set the status and headers instead of\n # waiting to do it manually, so that the class can handle any\n # special logic\n rv = self.response_class(rv, status=status, headers=headers)\n status = headers = None\n elif isinstance(rv, dict):\n rv = jsonify(rv)\n elif isinstance(rv, BaseResponse) or callable(rv):\n # evaluate a WSGI callable, or coerce a different response\n # class to the correct type\n try:\n rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B950\n except TypeError as e:\n raise TypeError(\n f\"{e}\\nThe view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, tuple, Response instance, or WSGI\"\n f\" callable, but it was a {type(rv).__name__}.\"\n ).with_traceback(sys.exc_info()[2])\n else:\n raise TypeError(\n \"The view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, tuple, Response instance, or WSGI\"\n f\" callable, but it was a {type(rv).__name__}.\"\n )\n\n rv = t.cast(Response, rv)\n # prefer the status if it was provided\n if status is not None:\n if isinstance(status, (str, bytes, bytearray)):\n rv.status = status # type: ignore\n else:\n rv.status_code = status\n\n # extend existing headers with provided headers\n if headers:\n rv.headers.update(headers)\n\n return rv"},{"col":4,"comment":"null","endLoc":364,"header":"def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SecureCookieSession]","id":388,"name":"open_session","nodeType":"Function","startLoc":350,"text":"def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SecureCookieSession]:\n s = self.get_signing_serializer(app)\n if s is None:\n return None\n val = request.cookies.get(self.get_cookie_name(app))\n if not val:\n return self.session_class()\n max_age = int(app.permanent_session_lifetime.total_seconds())\n try:\n data = s.loads(val, max_age=max_age)\n return self.session_class(data)\n except BadSignature:\n return self.session_class()"},{"col":4,"comment":"Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for\n the :func:`url_for` function is prefixed with the name of the blueprint.\n ","endLoc":369,"header":"def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n **options: t.Any,\n ) -> None","id":389,"name":"add_url_rule","nodeType":"Function","startLoc":353,"text":"def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for\n the :func:`url_for` function is prefixed with the name of the blueprint.\n \"\"\"\n if endpoint:\n assert \".\" not in endpoint, \"Blueprint endpoints should not contain dots\"\n if view_func and hasattr(view_func, \"__name__\"):\n assert (\n \".\" not in view_func.__name__\n ), \"Blueprint view function name should not contain dots\"\n self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))"},{"col":20,"endLoc":369,"id":390,"nodeType":"Lambda","startLoc":369,"text":"lambda s: s.add_url_rule(rule, endpoint, view_func, **options)"},{"col":4,"comment":"Register a custom template filter, available application wide. Like\n :meth:`Flask.template_filter` but for a blueprint.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n ","endLoc":383,"header":"def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable","id":391,"name":"app_template_filter","nodeType":"Function","startLoc":371,"text":"def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template filter, available application wide. Like\n :meth:`Flask.template_filter` but for a blueprint.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:\n self.add_app_template_filter(f, name=name)\n return f\n\n return decorator"},{"col":4,"comment":"Register a custom template filter, available application wide. Like\n :meth:`Flask.add_template_filter` but for a blueprint. Works exactly\n like the :meth:`app_template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n ","endLoc":399,"header":"def add_app_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None","id":392,"name":"add_app_template_filter","nodeType":"Function","startLoc":385,"text":"def add_app_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template filter, available application wide. Like\n :meth:`Flask.add_template_filter` but for a blueprint. Works exactly\n like the :meth:`app_template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.filters[name or f.__name__] = f\n\n self.record_once(register_template)"},{"col":4,"comment":"Register a custom template test, available application wide. Like\n :meth:`Flask.template_test` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n ","endLoc":415,"header":"def app_template_test(self, name: t.Optional[str] = None) -> t.Callable","id":393,"name":"app_template_test","nodeType":"Function","startLoc":401,"text":"def app_template_test(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template test, available application wide. Like\n :meth:`Flask.template_test` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateTestCallable) -> TemplateTestCallable:\n self.add_app_template_test(f, name=name)\n return f\n\n return decorator"},{"col":4,"comment":"Called before the request is dispatched. Calls\n :attr:`url_value_preprocessors` registered with the app and the\n current blueprint (if any). Then calls :attr:`before_request_funcs`\n registered with the app and the blueprint.\n\n If any :meth:`before_request` handler returns a non-None value, the\n value is handled as if it was the return value from the view, and\n further request handling is stopped.\n ","endLoc":1843,"header":"def preprocess_request(self) -> t.Optional[ResponseReturnValue]","id":394,"name":"preprocess_request","nodeType":"Function","startLoc":1814,"text":"def preprocess_request(self) -> t.Optional[ResponseReturnValue]:\n \"\"\"Called before the request is dispatched. Calls\n :attr:`url_value_preprocessors` registered with the app and the\n current blueprint (if any). Then calls :attr:`before_request_funcs`\n registered with the app and the blueprint.\n\n If any :meth:`before_request` handler returns a non-None value, the\n value is handled as if it was the return value from the view, and\n further request handling is stopped.\n \"\"\"\n\n funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[\n None\n ]\n for bp in self._request_blueprints():\n if bp in self.url_value_preprocessors:\n funcs = chain(funcs, self.url_value_preprocessors[bp])\n for func in funcs:\n func(request.endpoint, request.view_args)\n\n funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]\n for bp in self._request_blueprints():\n if bp in self.before_request_funcs:\n funcs = chain(funcs, self.before_request_funcs[bp])\n for func in funcs:\n rv = self.ensure_sync(func)()\n if rv is not None:\n return rv\n\n return None"},{"col":4,"comment":"Register a custom template test, available application wide. Like\n :meth:`Flask.add_template_test` but for a blueprint. Works exactly\n like the :meth:`app_template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n ","endLoc":433,"header":"def add_app_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None","id":395,"name":"add_app_template_test","nodeType":"Function","startLoc":417,"text":"def add_app_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template test, available application wide. Like\n :meth:`Flask.add_template_test` but for a blueprint. Works exactly\n like the :meth:`app_template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.tests[name or f.__name__] = f\n\n self.record_once(register_template)"},{"col":4,"comment":"Register a custom template global, available application wide. Like\n :meth:`Flask.template_global` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n ","endLoc":449,"header":"def app_template_global(self, name: t.Optional[str] = None) -> t.Callable","id":396,"name":"app_template_global","nodeType":"Function","startLoc":435,"text":"def app_template_global(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"Register a custom template global, available application wide. Like\n :meth:`Flask.template_global` but for a blueprint.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:\n self.add_app_template_global(f, name=name)\n return f\n\n return decorator"},{"col":0,"comment":"Serialize data to JSON and wrap it in a :class:`~flask.Response`\n with the :mimetype:`application/json` mimetype.\n\n Uses :func:`dumps` to serialize the data, but ``args`` and\n ``kwargs`` are treated as data rather than arguments to\n :func:`json.dumps`.\n\n 1. Single argument: Treated as a single value.\n 2. Multiple arguments: Treated as a list of values.\n ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.\n 3. Keyword arguments: Treated as a dict of values.\n ``jsonify(data=data, errors=errors)`` is the same as\n ``jsonify({\"data\": data, \"errors\": errors})``.\n 4. Passing both arguments and keyword arguments is not allowed as\n it's not clear what should happen.\n\n .. code-block:: python\n\n from flask import jsonify\n\n @app.route(\"/users/me\")\n def get_current_user():\n return jsonify(\n username=g.user.username,\n email=g.user.email,\n id=g.user.id,\n )\n\n Will return a JSON response like this:\n\n .. code-block:: javascript\n\n {\n \"username\": \"admin\",\n \"email\": \"admin@localhost\",\n \"id\": 42\n }\n\n The default output omits indents and spaces after separators. In\n debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,\n the output will be formatted to be easier to read.\n\n .. versionchanged:: 0.11\n Added support for serializing top-level arrays. This introduces\n a security risk in ancient browsers. See :ref:`security-json`.\n\n .. versionadded:: 0.2\n ","endLoc":350,"header":"def jsonify(*args: t.Any, **kwargs: t.Any) -> \"Response\"","id":397,"name":"jsonify","nodeType":"Function","startLoc":284,"text":"def jsonify(*args: t.Any, **kwargs: t.Any) -> \"Response\":\n \"\"\"Serialize data to JSON and wrap it in a :class:`~flask.Response`\n with the :mimetype:`application/json` mimetype.\n\n Uses :func:`dumps` to serialize the data, but ``args`` and\n ``kwargs`` are treated as data rather than arguments to\n :func:`json.dumps`.\n\n 1. Single argument: Treated as a single value.\n 2. Multiple arguments: Treated as a list of values.\n ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.\n 3. Keyword arguments: Treated as a dict of values.\n ``jsonify(data=data, errors=errors)`` is the same as\n ``jsonify({\"data\": data, \"errors\": errors})``.\n 4. Passing both arguments and keyword arguments is not allowed as\n it's not clear what should happen.\n\n .. code-block:: python\n\n from flask import jsonify\n\n @app.route(\"/users/me\")\n def get_current_user():\n return jsonify(\n username=g.user.username,\n email=g.user.email,\n id=g.user.id,\n )\n\n Will return a JSON response like this:\n\n .. code-block:: javascript\n\n {\n \"username\": \"admin\",\n \"email\": \"admin@localhost\",\n \"id\": 42\n }\n\n The default output omits indents and spaces after separators. In\n debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,\n the output will be formatted to be easier to read.\n\n .. versionchanged:: 0.11\n Added support for serializing top-level arrays. This introduces\n a security risk in ancient browsers. See :ref:`security-json`.\n\n .. versionadded:: 0.2\n \"\"\"\n indent = None\n separators = (\",\", \":\")\n\n if current_app.config[\"JSONIFY_PRETTYPRINT_REGULAR\"] or current_app.debug:\n indent = 2\n separators = (\", \", \": \")\n\n if args and kwargs:\n raise TypeError(\"jsonify() behavior undefined when passed both args and kwargs\")\n elif len(args) == 1: # single args are passed directly to dumps()\n data = args[0]\n else:\n data = args or kwargs\n\n return current_app.response_class(\n f\"{dumps(data, indent=indent, separators=separators)}\\n\",\n mimetype=current_app.config[\"JSONIFY_MIMETYPE\"],\n )"},{"col":4,"comment":"Register a custom template global, available application wide. Like\n :meth:`Flask.add_template_global` but for a blueprint. Works exactly\n like the :meth:`app_template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n ","endLoc":467,"header":"def add_app_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None","id":398,"name":"add_app_template_global","nodeType":"Function","startLoc":451,"text":"def add_app_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template global, available application wide. Like\n :meth:`Flask.add_template_global` but for a blueprint. Works exactly\n like the :meth:`app_template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.globals[name or f.__name__] = f\n\n self.record_once(register_template)"},{"col":4,"comment":"Like :meth:`Flask.before_request`. Such a function is executed\n before each request, even if outside of a blueprint.\n ","endLoc":476,"header":"def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable","id":399,"name":"before_app_request","nodeType":"Function","startLoc":469,"text":"def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:\n \"\"\"Like :meth:`Flask.before_request`. Such a function is executed\n before each request, even if outside of a blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n )\n return f"},{"col":12,"endLoc":474,"id":400,"nodeType":"Lambda","startLoc":474,"text":"lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)"},{"col":4,"comment":"This method is called to create the default ``OPTIONS`` response.\n This can be changed through subclassing to change the default\n behavior of ``OPTIONS`` responses.\n\n .. versionadded:: 0.7\n ","endLoc":1561,"header":"def make_default_options_response(self) -> Response","id":401,"name":"make_default_options_response","nodeType":"Function","startLoc":1550,"text":"def make_default_options_response(self) -> Response:\n \"\"\"This method is called to create the default ``OPTIONS`` response.\n This can be changed through subclassing to change the default\n behavior of ``OPTIONS`` responses.\n\n .. versionadded:: 0.7\n \"\"\"\n adapter = _request_ctx_stack.top.url_adapter\n methods = adapter.allowed_methods()\n rv = self.response_class()\n rv.allow.update(methods)\n return rv"},{"col":4,"comment":"Like :meth:`Flask.before_first_request`. Such a function is\n executed before the first request to the application.\n ","endLoc":485,"header":"def before_app_first_request(\n self, f: BeforeRequestCallable\n ) -> BeforeRequestCallable","id":402,"name":"before_app_first_request","nodeType":"Function","startLoc":478,"text":"def before_app_first_request(\n self, f: BeforeRequestCallable\n ) -> BeforeRequestCallable:\n \"\"\"Like :meth:`Flask.before_first_request`. Such a function is\n executed before the first request to the application.\n \"\"\"\n self.record_once(lambda s: s.app.before_first_request_funcs.append(f))\n return f"},{"col":25,"endLoc":484,"id":403,"nodeType":"Lambda","startLoc":484,"text":"lambda s: s.app.before_first_request_funcs.append(f)"},{"col":4,"comment":"Like :meth:`Flask.after_request` but for a blueprint. Such a function\n is executed after each request, even if outside of the blueprint.\n ","endLoc":494,"header":"def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable","id":404,"name":"after_app_request","nodeType":"Function","startLoc":487,"text":"def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:\n \"\"\"Like :meth:`Flask.after_request` but for a blueprint. Such a function\n is executed after each request, even if outside of the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n )\n return f"},{"col":12,"endLoc":492,"id":405,"nodeType":"Lambda","startLoc":492,"text":"lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)"},{"col":4,"comment":"This is called to figure out if an error should be ignored\n or not as far as the teardown system is concerned. If this\n function returns ``True`` then the teardown handlers will not be\n passed the error.\n\n .. versionadded:: 0.10\n ","endLoc":1571,"header":"def should_ignore_error(self, error: t.Optional[BaseException]) -> bool","id":406,"name":"should_ignore_error","nodeType":"Function","startLoc":1563,"text":"def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:\n \"\"\"This is called to figure out if an error should be ignored\n or not as far as the teardown system is concerned. If this\n function returns ``True`` then the teardown handlers will not be\n passed the error.\n\n .. versionadded:: 0.10\n \"\"\"\n return False"},{"col":4,"comment":"Creates a URL adapter for the given request. The URL adapter\n is created at a point where the request context is not yet set\n up so the request is passed explicitly.\n\n .. versionadded:: 0.6\n\n .. versionchanged:: 0.9\n This can now also be called without a request object when the\n URL adapter is created for the application context.\n\n .. versionchanged:: 1.0\n :data:`SERVER_NAME` no longer implicitly enables subdomain\n matching. Use :attr:`subdomain_matching` instead.\n ","endLoc":1775,"header":"def create_url_adapter(\n self, request: t.Optional[Request]\n ) -> t.Optional[MapAdapter]","id":407,"name":"create_url_adapter","nodeType":"Function","startLoc":1735,"text":"def create_url_adapter(\n self, request: t.Optional[Request]\n ) -> t.Optional[MapAdapter]:\n \"\"\"Creates a URL adapter for the given request. The URL adapter\n is created at a point where the request context is not yet set\n up so the request is passed explicitly.\n\n .. versionadded:: 0.6\n\n .. versionchanged:: 0.9\n This can now also be called without a request object when the\n URL adapter is created for the application context.\n\n .. versionchanged:: 1.0\n :data:`SERVER_NAME` no longer implicitly enables subdomain\n matching. Use :attr:`subdomain_matching` instead.\n \"\"\"\n if request is not None:\n # If subdomain matching is disabled (the default), use the\n # default subdomain in all cases. This should be the default\n # in Werkzeug but it currently does not have that feature.\n if not self.subdomain_matching:\n subdomain = self.url_map.default_subdomain or None\n else:\n subdomain = None\n\n return self.url_map.bind_to_environ(\n request.environ,\n server_name=self.config[\"SERVER_NAME\"],\n subdomain=subdomain,\n )\n # We need at the very least the server name to be set for this\n # to work.\n if self.config[\"SERVER_NAME\"] is not None:\n return self.url_map.bind(\n self.config[\"SERVER_NAME\"],\n script_name=self.config[\"APPLICATION_ROOT\"],\n url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n )\n\n return None"},{"col":4,"comment":"null","endLoc":404,"header":"def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None","id":408,"name":"save_session","nodeType":"Function","startLoc":366,"text":"def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None:\n name = self.get_cookie_name(app)\n domain = self.get_cookie_domain(app)\n path = self.get_cookie_path(app)\n secure = self.get_cookie_secure(app)\n samesite = self.get_cookie_samesite(app)\n\n # If the session is modified to be empty, remove the cookie.\n # If the session is empty, return without setting the cookie.\n if not session:\n if session.modified:\n response.delete_cookie(\n name, domain=domain, path=path, secure=secure, samesite=samesite\n )\n\n return\n\n # Add a \"Vary: Cookie\" header if the session was accessed at all.\n if session.accessed:\n response.vary.add(\"Cookie\")\n\n if not self.should_set_cookie(app, session):\n return\n\n httponly = self.get_cookie_httponly(app)\n expires = self.get_expiration_time(app, session)\n val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore\n response.set_cookie(\n name,\n val, # type: ignore\n expires=expires,\n httponly=httponly,\n domain=domain,\n path=path,\n secure=secure,\n samesite=samesite,\n )"},{"col":4,"comment":"Injects the URL defaults for the given endpoint directly into\n the values dictionary passed. This is used internally and\n automatically called on URL building.\n\n .. versionadded:: 0.7\n ","endLoc":1789,"header":"def inject_url_defaults(self, endpoint: str, values: dict) -> None","id":409,"name":"inject_url_defaults","nodeType":"Function","startLoc":1777,"text":"def inject_url_defaults(self, endpoint: str, values: dict) -> None:\n \"\"\"Injects the URL defaults for the given endpoint directly into\n the values dictionary passed. This is used internally and\n automatically called on URL building.\n\n .. versionadded:: 0.7\n \"\"\"\n funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]\n if \".\" in endpoint:\n bp = endpoint.rsplit(\".\", 1)[0]\n funcs = chain(funcs, self.url_default_functions[bp])\n for func in funcs:\n func(endpoint, values)"},{"col":4,"comment":"Like :meth:`Flask.teardown_request` but for a blueprint. Such a\n function is executed when tearing down each request, even if outside of\n the blueprint.\n ","endLoc":504,"header":"def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable","id":410,"name":"teardown_app_request","nodeType":"Function","startLoc":496,"text":"def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:\n \"\"\"Like :meth:`Flask.teardown_request` but for a blueprint. Such a\n function is executed when tearing down each request, even if outside of\n the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n )\n return f"},{"col":12,"endLoc":502,"id":411,"nodeType":"Lambda","startLoc":502,"text":"lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)"},{"col":4,"comment":"Like :meth:`Flask.context_processor` but for a blueprint. Such a\n function is executed each request, even if outside of the blueprint.\n ","endLoc":515,"header":"def app_context_processor(\n self, f: TemplateContextProcessorCallable\n ) -> TemplateContextProcessorCallable","id":412,"name":"app_context_processor","nodeType":"Function","startLoc":506,"text":"def app_context_processor(\n self, f: TemplateContextProcessorCallable\n ) -> TemplateContextProcessorCallable:\n \"\"\"Like :meth:`Flask.context_processor` but for a blueprint. Such a\n function is executed each request, even if outside of the blueprint.\n \"\"\"\n self.record_once(\n lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n )\n return f"},{"col":4,"comment":"Handle :class:`~werkzeug.routing.BuildError` on\n :meth:`url_for`.\n ","endLoc":1812,"header":"def handle_url_build_error(\n self, error: Exception, endpoint: str, values: dict\n ) -> str","id":413,"name":"handle_url_build_error","nodeType":"Function","startLoc":1791,"text":"def handle_url_build_error(\n self, error: Exception, endpoint: str, values: dict\n ) -> str:\n \"\"\"Handle :class:`~werkzeug.routing.BuildError` on\n :meth:`url_for`.\n \"\"\"\n for handler in self.url_build_error_handlers:\n try:\n rv = handler(error, endpoint, values)\n except BuildError as e:\n # make error available outside except block\n error = e\n else:\n if rv is not None:\n return rv\n\n # Re-raise if called with an active exception, otherwise raise\n # the passed in exception.\n if error is sys.exc_info()[1]:\n raise\n\n raise error"},{"col":12,"endLoc":513,"id":414,"nodeType":"Lambda","startLoc":513,"text":"lambda s: s.app.template_context_processors.setdefault(None, []).append(f)"},{"col":4,"comment":"Like :meth:`Flask.errorhandler` but for a blueprint. This\n handler is used for all requests, even if outside of the blueprint.\n ","endLoc":526,"header":"def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable","id":415,"name":"app_errorhandler","nodeType":"Function","startLoc":517,"text":"def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:\n \"\"\"Like :meth:`Flask.errorhandler` but for a blueprint. This\n handler is used for all requests, even if outside of the blueprint.\n \"\"\"\n\n def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:\n self.record_once(lambda s: s.app.errorhandler(code)(f))\n return f\n\n return decorator"},{"col":29,"endLoc":523,"id":416,"nodeType":"Lambda","startLoc":523,"text":"lambda s: s.app.errorhandler(code)(f)"},{"col":4,"comment":"Same as :meth:`url_value_preprocessor` but application wide.","endLoc":535,"header":"def app_url_value_preprocessor(\n self, f: URLValuePreprocessorCallable\n ) -> URLValuePreprocessorCallable","id":417,"name":"app_url_value_preprocessor","nodeType":"Function","startLoc":528,"text":"def app_url_value_preprocessor(\n self, f: URLValuePreprocessorCallable\n ) -> URLValuePreprocessorCallable:\n \"\"\"Same as :meth:`url_value_preprocessor` but application wide.\"\"\"\n self.record_once(\n lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n )\n return f"},{"col":4,"comment":"Can be overridden in order to modify the response object\n before it's sent to the WSGI server. By default this will\n call all the :meth:`after_request` decorated functions.\n\n .. versionchanged:: 0.5\n As of Flask 0.5 the functions registered for after request\n execution are called in reverse order of registration.\n\n :param response: a :attr:`response_class` object.\n :return: a new response object or the same, has to be an\n instance of :attr:`response_class`.\n ","endLoc":1869,"header":"def process_response(self, response: Response) -> Response","id":418,"name":"process_response","nodeType":"Function","startLoc":1845,"text":"def process_response(self, response: Response) -> Response:\n \"\"\"Can be overridden in order to modify the response object\n before it's sent to the WSGI server. By default this will\n call all the :meth:`after_request` decorated functions.\n\n .. versionchanged:: 0.5\n As of Flask 0.5 the functions registered for after request\n execution are called in reverse order of registration.\n\n :param response: a :attr:`response_class` object.\n :return: a new response object or the same, has to be an\n instance of :attr:`response_class`.\n \"\"\"\n ctx = _request_ctx_stack.top\n funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions\n for bp in self._request_blueprints():\n if bp in self.after_request_funcs:\n funcs = chain(funcs, reversed(self.after_request_funcs[bp]))\n if None in self.after_request_funcs:\n funcs = chain(funcs, reversed(self.after_request_funcs[None]))\n for handler in funcs:\n response = self.ensure_sync(handler)(response)\n if not self.session_interface.is_null_session(ctx.session):\n self.session_interface.save_session(self, ctx.session, response)\n return response"},{"col":12,"endLoc":533,"id":419,"nodeType":"Lambda","startLoc":533,"text":"lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)"},{"col":4,"comment":"Same as :meth:`url_defaults` but application wide.","endLoc":542,"header":"def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable","id":421,"name":"app_url_defaults","nodeType":"Function","startLoc":537,"text":"def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:\n \"\"\"Same as :meth:`url_defaults` but application wide.\"\"\"\n self.record_once(\n lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n )\n return f"},{"col":12,"endLoc":540,"id":422,"nodeType":"Lambda","startLoc":540,"text":"lambda s: s.app.url_default_functions.setdefault(None, []).append(f)"},{"attributeType":"null","col":4,"comment":"null","endLoc":161,"id":423,"name":"warn_on_modifications","nodeType":"Attribute","startLoc":161,"text":"warn_on_modifications"},{"attributeType":"null","col":4,"comment":"null","endLoc":162,"id":424,"name":"_got_registered_once","nodeType":"Attribute","startLoc":162,"text":"_got_registered_once"},{"col":4,"comment":"Called after the request is dispatched and the response is\n returned, right before the request context is popped.\n\n This calls all functions decorated with\n :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`\n if a blueprint handled the request. Finally, the\n :data:`request_tearing_down` signal is sent.\n\n This is called by\n :meth:`RequestContext.pop() `,\n which may be delayed during testing to maintain access to\n resources.\n\n :param exc: An unhandled exception raised while dispatching the\n request. Detected from the current exception information if\n not passed. Passed to each teardown function.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n ","endLoc":1904,"header":"def do_teardown_request(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None","id":425,"name":"do_teardown_request","nodeType":"Function","startLoc":1871,"text":"def do_teardown_request(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called after the request is dispatched and the response is\n returned, right before the request context is popped.\n\n This calls all functions decorated with\n :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`\n if a blueprint handled the request. Finally, the\n :data:`request_tearing_down` signal is sent.\n\n This is called by\n :meth:`RequestContext.pop() `,\n which may be delayed during testing to maintain access to\n resources.\n\n :param exc: An unhandled exception raised while dispatching the\n request. Detected from the current exception information if\n not passed. Passed to each teardown function.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n funcs: t.Iterable[TeardownCallable] = reversed(\n self.teardown_request_funcs[None]\n )\n for bp in self._request_blueprints():\n if bp in self.teardown_request_funcs:\n funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))\n for func in funcs:\n self.ensure_sync(func)(exc)\n request_tearing_down.send(self, exc=exc)"},{"col":4,"comment":"Called right before the application context is popped.\n\n When handling a request, the application context is popped\n after the request context. See :meth:`do_teardown_request`.\n\n This calls all functions decorated with\n :meth:`teardown_appcontext`. Then the\n :data:`appcontext_tearing_down` signal is sent.\n\n This is called by\n :meth:`AppContext.pop() `.\n\n .. versionadded:: 0.9\n ","endLoc":1927,"header":"def do_teardown_appcontext(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None","id":426,"name":"do_teardown_appcontext","nodeType":"Function","startLoc":1906,"text":"def do_teardown_appcontext(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called right before the application context is popped.\n\n When handling a request, the application context is popped\n after the request context. See :meth:`do_teardown_request`.\n\n This calls all functions decorated with\n :meth:`teardown_appcontext`. Then the\n :data:`appcontext_tearing_down` signal is sent.\n\n This is called by\n :meth:`AppContext.pop() `.\n\n .. versionadded:: 0.9\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n for func in reversed(self.teardown_appcontext_funcs):\n self.ensure_sync(func)(exc)\n appcontext_tearing_down.send(self, exc=exc)"},{"col":4,"comment":"Create an :class:`~flask.ctx.AppContext`. Use as a ``with``\n block to push the context, which will make :data:`current_app`\n point at this application.\n\n An application context is automatically pushed by\n :meth:`RequestContext.push() `\n when handling a request, and when running a CLI command. Use\n this to manually create a context outside of these situations.\n\n ::\n\n with app.app_context():\n init_db()\n\n See :doc:`/appcontext`.\n\n .. versionadded:: 0.9\n ","endLoc":1948,"header":"def app_context(self) -> AppContext","id":427,"name":"app_context","nodeType":"Function","startLoc":1929,"text":"def app_context(self) -> AppContext:\n \"\"\"Create an :class:`~flask.ctx.AppContext`. Use as a ``with``\n block to push the context, which will make :data:`current_app`\n point at this application.\n\n An application context is automatically pushed by\n :meth:`RequestContext.push() `\n when handling a request, and when running a CLI command. Use\n this to manually create a context outside of these situations.\n\n ::\n\n with app.app_context():\n init_db()\n\n See :doc:`/appcontext`.\n\n .. versionadded:: 0.9\n \"\"\"\n return AppContext(self)"},{"col":4,"comment":"Create a :class:`~flask.ctx.RequestContext` representing a\n WSGI environment. Use a ``with`` block to push the context,\n which will make :data:`request` point at this request.\n\n See :doc:`/reqcontext`.\n\n Typically you should not call this from your own code. A request\n context is automatically pushed by the :meth:`wsgi_app` when\n handling a request. Use :meth:`test_request_context` to create\n an environment and context instead of this method.\n\n :param environ: a WSGI environment\n ","endLoc":1964,"header":"def request_context(self, environ: dict) -> RequestContext","id":428,"name":"request_context","nodeType":"Function","startLoc":1950,"text":"def request_context(self, environ: dict) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` representing a\n WSGI environment. Use a ``with`` block to push the context,\n which will make :data:`request` point at this request.\n\n See :doc:`/reqcontext`.\n\n Typically you should not call this from your own code. A request\n context is automatically pushed by the :meth:`wsgi_app` when\n handling a request. Use :meth:`test_request_context` to create\n an environment and context instead of this method.\n\n :param environ: a WSGI environment\n \"\"\"\n return RequestContext(self, environ)"},{"attributeType":"null","col":4,"comment":"null","endLoc":166,"id":429,"name":"json_encoder","nodeType":"Attribute","startLoc":166,"text":"json_encoder"},{"attributeType":"null","col":4,"comment":"null","endLoc":169,"id":430,"name":"json_decoder","nodeType":"Attribute","startLoc":169,"text":"json_decoder"},{"attributeType":"null","col":8,"comment":"null","endLoc":201,"id":431,"name":"_blueprints","nodeType":"Attribute","startLoc":201,"text":"self._blueprints"},{"attributeType":"null","col":8,"comment":"null","endLoc":200,"id":432,"name":"cli_group","nodeType":"Attribute","startLoc":200,"text":"self.cli_group"},{"col":4,"comment":"null","endLoc":235,"header":"def __init__(self, app: \"Flask\") -> None","id":433,"name":"__init__","nodeType":"Function","startLoc":228,"text":"def __init__(self, app: \"Flask\") -> None:\n self.app = app\n self.url_adapter = app.create_url_adapter(None)\n self.g = app.app_ctx_globals_class()\n\n # Like request context, app contexts can be pushed multiple times\n # but there a basic \"refcount\" is enough to track them.\n self._refcnt = 0"},{"attributeType":"null","col":8,"comment":"null","endLoc":194,"id":434,"name":"deferred_functions","nodeType":"Attribute","startLoc":194,"text":"self.deferred_functions"},{"attributeType":"None","col":8,"comment":"null","endLoc":199,"id":435,"name":"url_values_defaults","nodeType":"Attribute","startLoc":199,"text":"self.url_values_defaults"},{"attributeType":"null","col":4,"comment":"null","endLoc":323,"id":436,"name":"salt","nodeType":"Attribute","startLoc":323,"text":"salt"},{"attributeType":"null","col":4,"comment":"null","endLoc":325,"id":437,"name":"digest_method","nodeType":"Attribute","startLoc":325,"text":"digest_method"},{"attributeType":"null","col":8,"comment":"null","endLoc":191,"id":438,"name":"name","nodeType":"Attribute","startLoc":191,"text":"self.name"},{"attributeType":"null","col":4,"comment":"null","endLoc":328,"id":439,"name":"key_derivation","nodeType":"Attribute","startLoc":328,"text":"key_derivation"},{"attributeType":"TaggedJSONSerializer","col":4,"comment":"null","endLoc":332,"id":441,"name":"serializer","nodeType":"Attribute","startLoc":332,"text":"serializer"},{"col":4,"comment":"Create a :class:`~flask.ctx.RequestContext` for a WSGI\n environment created from the given values. This is mostly useful\n during testing, where you may want to run a function that uses\n request data without dispatching a full request.\n\n See :doc:`/reqcontext`.\n\n Use a ``with`` block to push the context, which will make\n :data:`request` point at the request for the created\n environment. ::\n\n with test_request_context(...):\n generate_report()\n\n When using the shell, it may be easier to push and pop the\n context manually to avoid indentation. ::\n\n ctx = app.test_request_context(...)\n ctx.push()\n ...\n ctx.pop()\n\n Takes the same arguments as Werkzeug's\n :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n the application. See the linked Werkzeug docs for most of the\n available arguments. Flask-specific behavior is listed here.\n\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to\n :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param data: The request body, either as a string or a dict of\n form keys and values.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n ","endLoc":2020,"header":"def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext","id":442,"name":"test_request_context","nodeType":"Function","startLoc":1966,"text":"def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` for a WSGI\n environment created from the given values. This is mostly useful\n during testing, where you may want to run a function that uses\n request data without dispatching a full request.\n\n See :doc:`/reqcontext`.\n\n Use a ``with`` block to push the context, which will make\n :data:`request` point at the request for the created\n environment. ::\n\n with test_request_context(...):\n generate_report()\n\n When using the shell, it may be easier to push and pop the\n context manually to avoid indentation. ::\n\n ctx = app.test_request_context(...)\n ctx.push()\n ...\n ctx.pop()\n\n Takes the same arguments as Werkzeug's\n :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n the application. See the linked Werkzeug docs for most of the\n available arguments. Flask-specific behavior is listed here.\n\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to\n :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param data: The request body, either as a string or a dict of\n form keys and values.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n from .testing import EnvironBuilder\n\n builder = EnvironBuilder(self, *args, **kwargs)\n\n try:\n return self.request_context(builder.get_environ())\n finally:\n builder.close()"},{"attributeType":"SecureCookieSession","col":4,"comment":"null","endLoc":333,"id":443,"name":"session_class","nodeType":"Attribute","startLoc":333,"text":"session_class"},{"attributeType":"null","col":17,"comment":"null","endLoc":2,"id":444,"name":"t","nodeType":"Attribute","startLoc":2,"text":"t"},{"attributeType":"null","col":32,"comment":"null","endLoc":15,"id":445,"name":"te","nodeType":"Attribute","startLoc":15,"text":"te"},{"attributeType":"TaggedJSONSerializer","col":0,"comment":"null","endLoc":313,"id":446,"name":"session_json_serializer","nodeType":"Attribute","startLoc":313,"text":"session_json_serializer"},{"col":0,"comment":"","endLoc":1,"header":"sessions.py#","id":447,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n import typing_extensions as te\n from .app import Flask\n from .wrappers import Request, Response\n\nsession_json_serializer = TaggedJSONSerializer()"},{"id":448,"name":"mongoengine.rst","nodeType":"TextFile","path":"docs/patterns","text":"MongoDB with MongoEngine\n========================\n\nUsing a document database like MongoDB is a common alternative to\nrelational SQL databases. This pattern shows how to use\n`MongoEngine`_, a document mapper library, to integrate with MongoDB.\n\nA running MongoDB server and `Flask-MongoEngine`_ are required. ::\n\n pip install flask-mongoengine\n\n.. _MongoEngine: http://mongoengine.org\n.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io\n\n\nConfiguration\n-------------\n\nBasic setup can be done by defining ``MONGODB_SETTINGS`` on\n``app.config`` and creating a ``MongoEngine`` instance. ::\n\n from flask import Flask\n from flask_mongoengine import MongoEngine\n\n app = Flask(__name__)\n app.config['MONGODB_SETTINGS'] = {\n \"db\": \"myapp\",\n }\n db = MongoEngine(app)\n\n\nMapping Documents\n-----------------\n\nTo declare a model that represents a Mongo document, create a class that\ninherits from ``Document`` and declare each of the fields. ::\n\n import mongoengine as me\n\n class Movie(me.Document):\n title = me.StringField(required=True)\n year = me.IntField()\n rated = me.StringField()\n director = me.StringField()\n actors = me.ListField()\n\nIf the document has nested fields, use ``EmbeddedDocument`` to\ndefined the fields of the embedded document and\n``EmbeddedDocumentField`` to declare it on the parent document. ::\n\n class Imdb(me.EmbeddedDocument):\n imdb_id = me.StringField()\n rating = me.DecimalField()\n votes = me.IntField()\n\n class Movie(me.Document):\n ...\n imdb = me.EmbeddedDocumentField(Imdb)\n\n\nCreating Data\n-------------\n\nInstantiate your document class with keyword arguments for the fields.\nYou can also assign values to the field attributes after instantiation.\nThen call ``doc.save()``. ::\n\n bttf = Movie(title=\"Back To The Future\", year=1985)\n bttf.actors = [\n \"Michael J. Fox\",\n \"Christopher Lloyd\"\n ]\n bttf.imdb = Imdb(imdb_id=\"tt0088763\", rating=8.5)\n bttf.save()\n\n\nQueries\n-------\n\nUse the class ``objects`` attribute to make queries. A keyword argument\nlooks for an equal value on the field. ::\n\n bttf = Movies.objects(title=\"Back To The Future\").get_or_404()\n\nQuery operators may be used by concatenating them with the field name\nusing a double-underscore. ``objects``, and queries returned by\ncalling it, are iterable. ::\n\n some_theron_movie = Movie.objects(actors__in=[\"Charlize Theron\"]).first()\n\n for recents in Movie.objects(year__gte=2017):\n print(recents.title)\n\n\nDocumentation\n-------------\n\nThere are many more ways to define and query documents with MongoEngine.\nFor more information, check out the `official documentation\n`_.\n\nFlask-MongoEngine adds helpful utilities on top of MongoEngine. Check\nout their `documentation `_ as well.\n"},{"col":4,"comment":"The actual WSGI application. This is not implemented in\n :meth:`__call__` so that middlewares can be applied without\n losing a reference to the app object. Instead of doing this::\n\n app = MyMiddleware(app)\n\n It's a better idea to do this instead::\n\n app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n Then you still have the original application object around and\n can continue to call methods on it.\n\n .. versionchanged:: 0.7\n Teardown events for the request and app contexts are called\n even if an unhandled error occurs. Other events may not be\n called depending on when an error occurs during dispatch.\n See :ref:`callbacks-and-errors`.\n\n :param environ: A WSGI environment.\n :param start_response: A callable accepting a status code,\n a list of headers, and an optional exception context to\n start the response.\n ","endLoc":2063,"header":"def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any","id":449,"name":"wsgi_app","nodeType":"Function","startLoc":2022,"text":"def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The actual WSGI application. This is not implemented in\n :meth:`__call__` so that middlewares can be applied without\n losing a reference to the app object. Instead of doing this::\n\n app = MyMiddleware(app)\n\n It's a better idea to do this instead::\n\n app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n Then you still have the original application object around and\n can continue to call methods on it.\n\n .. versionchanged:: 0.7\n Teardown events for the request and app contexts are called\n even if an unhandled error occurs. Other events may not be\n called depending on when an error occurs during dispatch.\n See :ref:`callbacks-and-errors`.\n\n :param environ: A WSGI environment.\n :param start_response: A callable accepting a status code,\n a list of headers, and an optional exception context to\n start the response.\n \"\"\"\n ctx = self.request_context(environ)\n error: t.Optional[BaseException] = None\n try:\n try:\n ctx.push()\n response = self.full_dispatch_request()\n except Exception as e:\n error = e\n response = self.handle_exception(e)\n except: # noqa: B001\n error = sys.exc_info()[1]\n raise\n return response(environ, start_response)\n finally:\n if self.should_ignore_error(error):\n error = None\n ctx.auto_pop(error)"},{"id":450,"name":"CONTRIBUTING.rst","nodeType":"TextFile","path":"","text":"How to contribute to Flask\n==========================\n\nThank you for considering contributing to Flask!\n\n\nSupport questions\n-----------------\n\nPlease don't use the issue tracker for this. The issue tracker is a tool\nto address bugs and feature requests in Flask itself. Use one of the\nfollowing resources for questions about using Flask or issues with your\nown code:\n\n- The ``#get-help`` channel on our Discord chat:\n https://discord.gg/pallets\n- The mailing list flask@python.org for long term discussion or larger\n issues.\n- Ask on `Stack Overflow`_. Search with Google first using:\n ``site:stackoverflow.com flask {search term, exception message, etc.}``\n\n.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?tab=Frequent\n\n\nReporting issues\n----------------\n\nInclude the following information in your post:\n\n- Describe what you expected to happen.\n- If possible, include a `minimal reproducible example`_ to help us\n identify the issue. This also helps check that the issue is not with\n your own code.\n- Describe what actually happened. Include the full traceback if there\n was an exception.\n- List your Python and Flask versions. If possible, check if this\n issue is already fixed in the latest releases or the latest code in\n the repository.\n\n.. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example\n\n\nSubmitting patches\n------------------\n\nIf there is not an open issue for what you want to submit, prefer\nopening one for discussion before working on a PR. You can work on any\nissue that doesn't have an open PR linked to it or a maintainer assigned\nto it. These show up in the sidebar. No need to ask if you can work on\nan issue that interests you.\n\nInclude the following in your patch:\n\n- Use `Black`_ to format your code. This and other tools will run\n automatically if you install `pre-commit`_ using the instructions\n below.\n- Include tests if your patch adds or changes code. Make sure the test\n fails without your patch.\n- Update any relevant docs pages and docstrings. Docs pages and\n docstrings should be wrapped at 72 characters.\n- Add an entry in ``CHANGES.rst``. Use the same style as other\n entries. Also include ``.. versionchanged::`` inline changelogs in\n relevant docstrings.\n\n.. _Black: https://black.readthedocs.io\n.. _pre-commit: https://pre-commit.com\n\n\nFirst time setup\n~~~~~~~~~~~~~~~~\n\n- Download and install the `latest version of git`_.\n- Configure git with your `username`_ and `email`_.\n\n .. code-block:: text\n\n $ git config --global user.name 'your name'\n $ git config --global user.email 'your email'\n\n- Make sure you have a `GitHub account`_.\n- Fork Flask to your GitHub account by clicking the `Fork`_ button.\n- `Clone`_ the main repository locally.\n\n .. code-block:: text\n\n $ git clone https://github.com/pallets/flask\n $ cd flask\n\n- Add your fork as a remote to push your work to. Replace\n ``{username}`` with your username. This names the remote \"fork\", the\n default Pallets remote is \"origin\".\n\n .. code-block:: text\n\n git remote add fork https://github.com/{username}/flask\n\n- Create a virtualenv.\n\n .. tabs::\n\n .. group-tab:: Linux/macOS\n\n .. code-block:: text\n\n $ python3 -m venv env\n $ . env/bin/activate\n\n .. group-tab:: Windows\n\n .. code-block:: text\n\n > py -3 -m venv env\n > env\\Scripts\\activate\n\n- Install the development dependencies, then install Flask in editable\n mode.\n\n .. code-block:: text\n\n $ pip install -r requirements/dev.txt && pip install -e .\n\n- Install the pre-commit hooks.\n\n .. code-block:: text\n\n $ pre-commit install\n\n.. _latest version of git: https://git-scm.com/downloads\n.. _username: https://docs.github.com/en/github/using-git/setting-your-username-in-git\n.. _email: https://docs.github.com/en/github/setting-up-and-managing-your-github-user-account/setting-your-commit-email-address\n.. _GitHub account: https://github.com/join\n.. _Fork: https://github.com/pallets/flask/fork\n.. _Clone: https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#step-2-create-a-local-clone-of-your-fork\n\n\nStart coding\n~~~~~~~~~~~~\n\n- Create a branch to identify the issue you would like to work on. If\n you're submitting a bug or documentation fix, branch off of the\n latest \".x\" branch.\n\n .. code-block:: text\n\n $ git fetch origin\n $ git checkout -b your-branch-name origin/2.0.x\n\n If you're submitting a feature addition or change, branch off of the\n \"main\" branch.\n\n .. code-block:: text\n\n $ git fetch origin\n $ git checkout -b your-branch-name origin/main\n\n- Using your favorite editor, make your changes,\n `committing as you go`_.\n- Include tests that cover any code changes you make. Make sure the\n test fails without your patch. Run the tests as described below.\n- Push your commits to your fork on GitHub and\n `create a pull request`_. Link to the issue being addressed with\n ``fixes #123`` in the pull request.\n\n .. code-block:: text\n\n $ git push --set-upstream fork your-branch-name\n\n.. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes\n.. _create a pull request: https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request\n\n\nRunning the tests\n~~~~~~~~~~~~~~~~~\n\nRun the basic test suite with pytest.\n\n.. code-block:: text\n\n $ pytest\n\nThis runs the tests for the current environment, which is usually\nsufficient. CI will run the full suite when you submit your pull\nrequest. You can run the full test suite with tox if you don't want to\nwait.\n\n.. code-block:: text\n\n $ tox\n\n\nRunning test coverage\n~~~~~~~~~~~~~~~~~~~~~\n\nGenerating a report of lines that do not have test coverage can indicate\nwhere to start contributing. Run ``pytest`` using ``coverage`` and\ngenerate a report.\n\n.. code-block:: text\n\n $ pip install coverage\n $ coverage run -m pytest\n $ coverage html\n\nOpen ``htmlcov/index.html`` in your browser to explore the report.\n\nRead more about `coverage `__.\n\n\nBuilding the docs\n~~~~~~~~~~~~~~~~~\n\nBuild the docs in the ``docs`` directory using Sphinx.\n\n.. code-block:: text\n\n $ cd docs\n $ make html\n\nOpen ``_build/html/index.html`` in your browser to view the docs.\n\nRead more about `Sphinx `__.\n"},{"id":451,"name":"docs/deploying","nodeType":"Package"},{"id":452,"name":"mod_wsgi.rst","nodeType":"TextFile","path":"docs/deploying","text":"mod_wsgi (Apache)\n=================\n\nIf you are using the `Apache`_ webserver, consider using `mod_wsgi`_.\n\n.. admonition:: Watch Out\n\n Please make sure in advance that any ``app.run()`` calls you might\n have in your application file are inside an ``if __name__ ==\n '__main__':`` block or moved to a separate file. Just make sure it's\n not called because this will always start a local WSGI server which\n we do not want if we deploy that application to mod_wsgi.\n\n.. _Apache: https://httpd.apache.org/\n\nInstalling `mod_wsgi`\n---------------------\n\nIf you don't have `mod_wsgi` installed yet you have to either install it\nusing a package manager or compile it yourself. The mod_wsgi\n`installation instructions`_ cover source installations on UNIX systems.\n\nIf you are using Ubuntu/Debian you can apt-get it and activate it as\nfollows:\n\n.. sourcecode:: text\n\n $ apt-get install libapache2-mod-wsgi-py3\n\nIf you are using a yum based distribution (Fedora, OpenSUSE, etc..) you\ncan install it as follows:\n\n.. sourcecode:: text\n\n $ yum install mod_wsgi\n\nOn FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by\nusing pkg_add:\n\n.. sourcecode:: text\n\n $ pkg install ap24-py37-mod_wsgi\n\nIf you are using pkgsrc you can install `mod_wsgi` by compiling the\n`www/ap2-wsgi` package.\n\nIf you encounter segfaulting child processes after the first apache\nreload you can safely ignore them. Just restart the server.\n\nCreating a `.wsgi` file\n-----------------------\n\nTo run your application you need a :file:`yourapplication.wsgi` file.\nThis file contains the code `mod_wsgi` is executing on startup\nto get the application object. The object called `application`\nin that file is then used as application.\n\nFor most applications the following file should be sufficient::\n\n from yourapplication import app as application\n\nIf a factory function is used in a :file:`__init__.py` file, then the function should be imported::\n\n from yourapplication import create_app\n application = create_app()\n\nIf you don't have a factory function for application creation but a singleton\ninstance you can directly import that one as `application`.\n\nStore that file somewhere that you will find it again (e.g.:\n:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all\nthe libraries that are in use are on the python load path. If you don't\nwant to install it system wide consider using a `virtual python`_\ninstance. Keep in mind that you will have to actually install your\napplication into the virtualenv as well. Alternatively there is the\noption to just patch the path in the ``.wsgi`` file before the import::\n\n import sys\n sys.path.insert(0, '/path/to/the/application')\n\nConfiguring Apache\n------------------\n\nThe last thing you have to do is to create an Apache configuration file\nfor your application. In this example we are telling `mod_wsgi` to\nexecute the application under a different user for security reasons:\n\n.. sourcecode:: apache\n\n \n ServerName example.com\n\n WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5\n WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi\n\n \n WSGIProcessGroup yourapplication\n WSGIApplicationGroup %{GLOBAL}\n Order deny,allow\n Allow from all\n \n \n\nNote: WSGIDaemonProcess isn't implemented in Windows and Apache will\nrefuse to run with the above configuration. On a Windows system, eliminate those lines:\n\n.. sourcecode:: apache\n\n \n ServerName example.com\n WSGIScriptAlias / C:\\yourdir\\yourapp.wsgi\n \n Order deny,allow\n Allow from all\n \n \n\nNote: There have been some changes in access control configuration\nfor `Apache 2.4`_.\n\n.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html\n\nMost notably, the syntax for directory permissions has changed from httpd 2.2\n\n.. sourcecode:: apache\n\n Order allow,deny\n Allow from all\n\nto httpd 2.4 syntax\n\n.. sourcecode:: apache\n\n Require all granted\n\n\nFor more information consult the `mod_wsgi documentation`_.\n\n.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi\n.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html\n.. _virtual python: https://pypi.org/project/virtualenv/\n.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html\n\nTroubleshooting\n---------------\n\nIf your application does not run, follow this guide to troubleshoot:\n\n**Problem:** application does not run, errorlog shows SystemExit ignored\n You have an ``app.run()`` call in your application file that is not\n guarded by an ``if __name__ == '__main__':`` condition. Either\n remove that :meth:`~flask.Flask.run` call from the file and move it\n into a separate :file:`run.py` file or put it into such an if block.\n\n**Problem:** application gives permission errors\n Probably caused by your application running as the wrong user. Make\n sure the folders the application needs access to have the proper\n privileges set and the application runs as the correct user\n (``user`` and ``group`` parameter to the `WSGIDaemonProcess`\n directive)\n\n**Problem:** application dies with an error on print\n Keep in mind that mod_wsgi disallows doing anything with\n :data:`sys.stdout` and :data:`sys.stderr`. You can disable this\n protection from the config by setting the `WSGIRestrictStdout` to\n ``off``:\n\n .. sourcecode:: apache\n\n WSGIRestrictStdout Off\n\n Alternatively you can also replace the standard out in the .wsgi file\n with a different stream::\n\n import sys\n sys.stdout = sys.stderr\n\n**Problem:** accessing resources gives IO errors\n Your application probably is a single .py file you symlinked into\n the site-packages folder. Please be aware that this does not work,\n instead you either have to put the folder into the pythonpath the\n file is stored in, or convert your application into a package.\n\n The reason for this is that for non-installed packages, the module\n filename is used to locate the resources and for symlinks the wrong\n filename is picked up.\n\nSupport for Automatic Reloading\n-------------------------------\n\nTo help deployment tools you can activate support for automatic\nreloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will\nreload all the daemon processes for us.\n\nFor that, just add the following directive to your `Directory` section:\n\n.. sourcecode:: apache\n\n WSGIScriptReloading On\n\nWorking with Virtual Environments\n---------------------------------\n\nVirtual environments have the advantage that they never install the\nrequired dependencies system wide so you have a better control over what\nis used where. If you want to use a virtual environment with mod_wsgi\nyou have to modify your ``.wsgi`` file slightly.\n\nAdd the following lines to the top of your ``.wsgi`` file::\n\n activate_this = '/path/to/env/bin/activate_this.py'\n with open(activate_this) as file_:\n exec(file_.read(), dict(__file__=activate_this))\n\nThis sets up the load paths according to the settings of the virtual\nenvironment. Keep in mind that the path has to be absolute.\n"},{"fileName":"tag.py","filePath":"src/flask/json","id":453,"nodeType":"File","text":"\"\"\"\nTagged JSON\n~~~~~~~~~~~\n\nA compact representation for lossless serialization of non-standard JSON\ntypes. :class:`~flask.sessions.SecureCookieSessionInterface` uses this\nto serialize the session data, but it may be useful in other places. It\ncan be extended to support other types.\n\n.. autoclass:: TaggedJSONSerializer\n :members:\n\n.. autoclass:: JSONTag\n :members:\n\nLet's see an example that adds support for\n:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so\nto handle this we will dump the items as a list of ``[key, value]``\npairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to\nidentify the type. The session serializer processes dicts first, so\ninsert the new tag at the front of the order since ``OrderedDict`` must\nbe processed before ``dict``.\n\n.. code-block:: python\n\n from flask.json.tag import JSONTag\n\n class TagOrderedDict(JSONTag):\n __slots__ = ('serializer',)\n key = ' od'\n\n def check(self, value):\n return isinstance(value, OrderedDict)\n\n def to_json(self, value):\n return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]\n\n def to_python(self, value):\n return OrderedDict(value)\n\n app.session_interface.serializer.register(TagOrderedDict, index=0)\n\"\"\"\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\n\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\n\nfrom ..json import dumps\nfrom ..json import loads\n\n\nclass JSONTag:\n \"\"\"Base class for defining type tags for :class:`TaggedJSONSerializer`.\"\"\"\n\n __slots__ = (\"serializer\",)\n\n #: The tag to mark the serialized object with. If ``None``, this tag is\n #: only used as an intermediate step during tagging.\n key: t.Optional[str] = None\n\n def __init__(self, serializer: \"TaggedJSONSerializer\") -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer\n\n def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError\n\n def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError\n\n def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}\n\n\nclass TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}\n\n\nclass PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json\n\n\nclass TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)\n\n\nclass PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json\n\n\nclass TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)\n\n\nclass TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)\n\n\nclass TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) -> t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)\n\n\nclass TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)\n\n\nclass TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) -> None:\n self.tags: t.Dict[str, JSONTag] = {}\n self.order: t.List[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: t.Type[JSONTag],\n force: bool = False,\n index: t.Optional[int] = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key is not None:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)\n\n def tag(self, value: t.Any) -> t.Dict[str, t.Any]:\n \"\"\"Convert a value to a tagged representation if necessary.\"\"\"\n for tag in self.order:\n if tag.check(value):\n return tag.tag(value)\n\n return value\n\n def untag(self, value: t.Dict[str, t.Any]) -> t.Any:\n \"\"\"Convert a tagged representation back to the original type.\"\"\"\n if len(value) != 1:\n return value\n\n key = next(iter(value))\n\n if key not in self.tags:\n return value\n\n return self.tags[key].to_python(value[key])\n\n def dumps(self, value: t.Any) -> str:\n \"\"\"Tag the value and dump it to a compact JSON string.\"\"\"\n return dumps(self.tag(value), separators=(\",\", \":\"))\n\n def loads(self, value: str) -> t.Any:\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return loads(value, object_hook=self.untag)\n"},{"className":"JSONTag","col":0,"comment":"Base class for defining type tags for :class:`TaggedJSONSerializer`.","endLoc":87,"id":454,"nodeType":"Class","startLoc":57,"text":"class JSONTag:\n \"\"\"Base class for defining type tags for :class:`TaggedJSONSerializer`.\"\"\"\n\n __slots__ = (\"serializer\",)\n\n #: The tag to mark the serialized object with. If ``None``, this tag is\n #: only used as an intermediate step during tagging.\n key: t.Optional[str] = None\n\n def __init__(self, serializer: \"TaggedJSONSerializer\") -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer\n\n def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError\n\n def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError\n\n def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}"},{"col":4,"comment":"Create a tagger for the given serializer.","endLoc":68,"header":"def __init__(self, serializer: \"TaggedJSONSerializer\") -> None","id":455,"name":"__init__","nodeType":"Function","startLoc":66,"text":"def __init__(self, serializer: \"TaggedJSONSerializer\") -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer"},{"col":4,"comment":"Check if the given value should be tagged by this tag.","endLoc":72,"header":"def check(self, value: t.Any) -> bool","id":456,"name":"check","nodeType":"Function","startLoc":70,"text":"def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError"},{"col":4,"comment":"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.","endLoc":77,"header":"def to_json(self, value: t.Any) -> t.Any","id":457,"name":"to_json","nodeType":"Function","startLoc":74,"text":"def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError"},{"col":4,"comment":"Convert the JSON representation back to the correct type. The tag\n will already be removed.","endLoc":82,"header":"def to_python(self, value: t.Any) -> t.Any","id":458,"name":"to_python","nodeType":"Function","startLoc":79,"text":"def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError"},{"col":4,"comment":"Convert the value to a valid JSON type and add the tag structure\n around it.","endLoc":87,"header":"def tag(self, value: t.Any) -> t.Any","id":459,"name":"tag","nodeType":"Function","startLoc":84,"text":"def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}"},{"col":4,"comment":"null","endLoc":82,"header":"def __init__(\n self,\n app: \"Flask\",\n path: str = \"/\",\n base_url: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_scheme: t.Optional[str] = None,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> None","id":460,"name":"__init__","nodeType":"Function","startLoc":44,"text":"def __init__(\n self,\n app: \"Flask\",\n path: str = \"/\",\n base_url: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_scheme: t.Optional[str] = None,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> None:\n assert not (base_url or subdomain or url_scheme) or (\n base_url is not None\n ) != bool(\n subdomain or url_scheme\n ), 'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n\n if base_url is None:\n http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n app_root = app.config[\"APPLICATION_ROOT\"]\n\n if subdomain:\n http_host = f\"{subdomain}.{http_host}\"\n\n if url_scheme is None:\n url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n url = url_parse(path)\n base_url = (\n f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n f\"/{app_root.lstrip('/')}\"\n )\n path = url.path\n\n if url.query:\n sep = b\"?\" if isinstance(url.query, bytes) else \"?\"\n path += sep + url.query\n\n self.app = app\n super().__init__(path, base_url, *args, **kwargs)"},{"attributeType":"None","col":8,"comment":"null","endLoc":193,"id":461,"name":"subdomain","nodeType":"Attribute","startLoc":193,"text":"self.subdomain"},{"attributeType":"None","col":8,"comment":"null","endLoc":192,"id":462,"name":"url_prefix","nodeType":"Attribute","startLoc":192,"text":"self.url_prefix"},{"col":4,"comment":"The WSGI server calls the Flask application object as the\n WSGI application. This calls :meth:`wsgi_app`, which can be\n wrapped to apply middleware.\n ","endLoc":2070,"header":"def __call__(self, environ: dict, start_response: t.Callable) -> t.Any","id":463,"name":"__call__","nodeType":"Function","startLoc":2065,"text":"def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The WSGI server calls the Flask application object as the\n WSGI application. This calls :meth:`wsgi_app`, which can be\n wrapped to apply middleware.\n \"\"\"\n return self.wsgi_app(environ, start_response)"},{"attributeType":"null","col":4,"comment":"null","endLoc":200,"id":464,"name":"request_class","nodeType":"Attribute","startLoc":200,"text":"request_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":60,"id":465,"name":"__slots__","nodeType":"Attribute","startLoc":60,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":204,"id":466,"name":"response_class","nodeType":"Attribute","startLoc":204,"text":"response_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":209,"id":467,"name":"jinja_environment","nodeType":"Attribute","startLoc":209,"text":"jinja_environment"},{"attributeType":"null","col":4,"comment":"null","endLoc":225,"id":468,"name":"app_ctx_globals_class","nodeType":"Attribute","startLoc":225,"text":"app_ctx_globals_class"},{"attributeType":"None","col":4,"comment":"null","endLoc":64,"id":469,"name":"key","nodeType":"Attribute","startLoc":64,"text":"key"},{"attributeType":"null","col":4,"comment":"null","endLoc":236,"id":470,"name":"config_class","nodeType":"Attribute","startLoc":236,"text":"config_class"},{"attributeType":"TaggedJSONSerializer","col":8,"comment":"null","endLoc":68,"id":471,"name":"serializer","nodeType":"Attribute","startLoc":68,"text":"self.serializer"},{"attributeType":"null","col":4,"comment":"null","endLoc":248,"id":472,"name":"testing","nodeType":"Attribute","startLoc":248,"text":"testing"},{"className":"TagDict","col":0,"comment":"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n ","endLoc":113,"id":473,"nodeType":"Class","startLoc":90,"text":"class TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}"},{"col":4,"comment":"null","endLoc":105,"header":"def check(self, value: t.Any) -> bool","id":474,"name":"check","nodeType":"Function","startLoc":100,"text":"def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )"},{"attributeType":"null","col":4,"comment":"null","endLoc":256,"id":475,"name":"secret_key","nodeType":"Attribute","startLoc":256,"text":"secret_key"},{"attributeType":"null","col":8,"comment":"null","endLoc":282,"id":476,"name":"_got_registered_once","nodeType":"Attribute","startLoc":282,"text":"self._got_registered_once"},{"attributeType":"null","col":4,"comment":"null","endLoc":262,"id":477,"name":"session_cookie_name","nodeType":"Attribute","startLoc":262,"text":"session_cookie_name"},{"col":4,"comment":"null","endLoc":109,"header":"def to_json(self, value: t.Any) -> t.Any","id":478,"name":"to_json","nodeType":"Function","startLoc":107,"text":"def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}"},{"attributeType":"null","col":4,"comment":"null","endLoc":271,"id":479,"name":"permanent_session_lifetime","nodeType":"Attribute","startLoc":271,"text":"permanent_session_lifetime"},{"attributeType":"null","col":4,"comment":"null","endLoc":285,"id":480,"name":"send_file_max_age_default","nodeType":"Attribute","startLoc":285,"text":"send_file_max_age_default"},{"col":0,"comment":"Executes a function after this request. This is useful to modify\n response objects. The function is passed the response object and has\n to return the same or a new one.\n\n Example::\n\n @app.route('/')\n def index():\n @after_this_request\n def add_header(response):\n response.headers['X-Foo'] = 'Parachute'\n return response\n return 'Hello World!'\n\n This is more useful if a function other than the view function wants to\n modify a response. For instance think of a decorator that wants to add\n some headers without converting the return value into a response object.\n\n .. versionadded:: 0.9\n ","endLoc":134,"header":"def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable","id":481,"name":"after_this_request","nodeType":"Function","startLoc":112,"text":"def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:\n \"\"\"Executes a function after this request. This is useful to modify\n response objects. The function is passed the response object and has\n to return the same or a new one.\n\n Example::\n\n @app.route('/')\n def index():\n @after_this_request\n def add_header(response):\n response.headers['X-Foo'] = 'Parachute'\n return response\n return 'Hello World!'\n\n This is more useful if a function other than the view function wants to\n modify a response. For instance think of a decorator that wants to add\n some headers without converting the return value into a response object.\n\n .. versionadded:: 0.9\n \"\"\"\n _request_ctx_stack.top._after_request_functions.append(f)\n return f"},{"attributeType":"null","col":4,"comment":"null","endLoc":297,"id":482,"name":"use_x_sendfile","nodeType":"Attribute","startLoc":297,"text":"use_x_sendfile"},{"col":4,"comment":"null","endLoc":332,"header":"def __init__(\n self,\n app: \"Flask\",\n environ: dict,\n request: t.Optional[\"Request\"] = None,\n session: t.Optional[\"SessionMixin\"] = None,\n ) -> None","id":483,"name":"__init__","nodeType":"Function","startLoc":296,"text":"def __init__(\n self,\n app: \"Flask\",\n environ: dict,\n request: t.Optional[\"Request\"] = None,\n session: t.Optional[\"SessionMixin\"] = None,\n ) -> None:\n self.app = app\n if request is None:\n request = app.request_class(environ)\n self.request = request\n self.url_adapter = None\n try:\n self.url_adapter = app.create_url_adapter(self.request)\n except HTTPException as e:\n self.request.routing_exception = e\n self.flashes = None\n self.session = session\n\n # Request contexts can be pushed multiple times and interleaved with\n # other request contexts. Now only if the last level is popped we\n # get rid of them. Additionally if an application context is missing\n # one is created implicitly so for each level we add this information\n self._implicit_app_ctx_stack: t.List[t.Optional[\"AppContext\"]] = []\n\n # indicator if the context was preserved. Next time another context\n # is pushed the preserved context is popped.\n self.preserved = False\n\n # remembers the exception for pop if there is one in case the context\n # preservation kicks in.\n self._preserved_exc = None\n\n # Functions that should be executed after the request on the response\n # object. These will be called before the regular \"after_request\"\n # functions.\n self._after_request_functions: t.List[AfterRequestCallable] = []"},{"attributeType":"null","col":4,"comment":"null","endLoc":302,"id":484,"name":"json_encoder","nodeType":"Attribute","startLoc":302,"text":"json_encoder"},{"col":0,"comment":"A helper function that decorates a function to retain the current\n request context. This is useful when working with greenlets. The moment\n the function is decorated a copy of the request context is created and\n then pushed when the function is called. The current session is also\n included in the copied request context.\n\n Example::\n\n import gevent\n from flask import copy_current_request_context\n\n @app.route('/')\n def index():\n @copy_current_request_context\n def do_some_work():\n # do some work here, it can access flask.request or\n # flask.session like you would otherwise in the view function.\n ...\n gevent.spawn(do_some_work)\n return 'Regular response'\n\n .. versionadded:: 0.10\n ","endLoc":174,"header":"def copy_current_request_context(f: t.Callable) -> t.Callable","id":485,"name":"copy_current_request_context","nodeType":"Function","startLoc":137,"text":"def copy_current_request_context(f: t.Callable) -> t.Callable:\n \"\"\"A helper function that decorates a function to retain the current\n request context. This is useful when working with greenlets. The moment\n the function is decorated a copy of the request context is created and\n then pushed when the function is called. The current session is also\n included in the copied request context.\n\n Example::\n\n import gevent\n from flask import copy_current_request_context\n\n @app.route('/')\n def index():\n @copy_current_request_context\n def do_some_work():\n # do some work here, it can access flask.request or\n # flask.session like you would otherwise in the view function.\n ...\n gevent.spawn(do_some_work)\n return 'Regular response'\n\n .. versionadded:: 0.10\n \"\"\"\n top = _request_ctx_stack.top\n if top is None:\n raise RuntimeError(\n \"This decorator can only be used at local scopes \"\n \"when a request context is on the stack. For instance within \"\n \"view functions.\"\n )\n reqctx = top.copy()\n\n def wrapper(*args, **kwargs):\n with reqctx:\n return f(*args, **kwargs)\n\n return update_wrapper(wrapper, f)"},{"attributeType":"null","col":4,"comment":"null","endLoc":307,"id":486,"name":"json_decoder","nodeType":"Attribute","startLoc":307,"text":"json_decoder"},{"attributeType":"null","col":4,"comment":"null","endLoc":318,"id":487,"name":"jinja_options","nodeType":"Attribute","startLoc":318,"text":"jinja_options"},{"attributeType":"null","col":4,"comment":"null","endLoc":321,"id":488,"name":"default_config","nodeType":"Attribute","startLoc":321,"text":"default_config"},{"attributeType":"null","col":4,"comment":"null","endLoc":359,"id":489,"name":"url_rule_class","nodeType":"Attribute","startLoc":359,"text":"url_rule_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":365,"id":490,"name":"url_map_class","nodeType":"Attribute","startLoc":365,"text":"url_map_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":370,"id":491,"name":"test_client_class","nodeType":"Attribute","startLoc":370,"text":"test_client_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":378,"id":492,"name":"test_cli_runner_class","nodeType":"Attribute","startLoc":378,"text":"test_cli_runner_class"},{"attributeType":"null","col":4,"comment":"null","endLoc":384,"id":493,"name":"session_interface","nodeType":"Attribute","startLoc":384,"text":"session_interface"},{"attributeType":"null","col":4,"comment":"null","endLoc":782,"id":494,"name":"env","nodeType":"Attribute","startLoc":782,"text":"env"},{"attributeType":"null","col":8,"comment":"null","endLoc":441,"id":495,"name":"before_first_request_funcs","nodeType":"Attribute","startLoc":441,"text":"self.before_first_request_funcs"},{"attributeType":"null","col":8,"comment":"null","endLoc":455,"id":496,"name":"shell_context_processors","nodeType":"Attribute","startLoc":455,"text":"self.shell_context_processors"},{"attributeType":"null","col":16,"comment":"null","endLoc":885,"id":497,"name":"debug","nodeType":"Attribute","startLoc":885,"text":"self.debug"},{"attributeType":"null","col":8,"comment":"null","endLoc":432,"id":498,"name":"url_build_error_handlers","nodeType":"Attribute","startLoc":432,"text":"self.url_build_error_handlers"},{"attributeType":"null","col":8,"comment":"null","endLoc":491,"id":499,"name":"url_map","nodeType":"Attribute","startLoc":491,"text":"self.url_map"},{"col":0,"comment":"Works like :func:`has_request_context` but for the application\n context. You can also just do a boolean check on the\n :data:`current_app` object instead.\n\n .. versionadded:: 0.9\n ","endLoc":216,"header":"def has_app_context() -> bool","id":500,"name":"has_app_context","nodeType":"Function","startLoc":209,"text":"def has_app_context() -> bool:\n \"\"\"Works like :func:`has_request_context` but for the application\n context. You can also just do a boolean check on the\n :data:`current_app` object instead.\n\n .. versionadded:: 0.9\n \"\"\"\n return _app_ctx_stack.top is not None"},{"col":0,"comment":"If you have code that wants to test if a request context is there or\n not this function can be used. For instance, you may want to take advantage\n of request information if the request object is available, but fail\n silently if it is unavailable.\n\n ::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and has_request_context():\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n Alternatively you can also just test any of the context bound objects\n (such as :class:`request` or :class:`g`) for truthness::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and request:\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n .. versionadded:: 0.7\n ","endLoc":206,"header":"def has_request_context() -> bool","id":501,"name":"has_request_context","nodeType":"Function","startLoc":177,"text":"def has_request_context() -> bool:\n \"\"\"If you have code that wants to test if a request context is there or\n not this function can be used. For instance, you may want to take advantage\n of request information if the request object is available, but fail\n silently if it is unavailable.\n\n ::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and has_request_context():\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n Alternatively you can also just test any of the context bound objects\n (such as :class:`request` or :class:`g`) for truthness::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and request:\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n .. versionadded:: 0.7\n \"\"\"\n return _request_ctx_stack.top is not None"},{"attributeType":"_AppCtxGlobals","col":0,"comment":"null","endLoc":59,"id":502,"name":"g","nodeType":"Attribute","startLoc":59,"text":"g"},{"attributeType":"null","col":16,"comment":"null","endLoc":884,"id":503,"name":"env","nodeType":"Attribute","startLoc":884,"text":"self.env"},{"attributeType":"null","col":8,"comment":"null","endLoc":463,"id":504,"name":"blueprints","nodeType":"Attribute","startLoc":463,"text":"self.blueprints"},{"attributeType":"null","col":8,"comment":"null","endLoc":474,"id":505,"name":"extensions","nodeType":"Attribute","startLoc":474,"text":"self.extensions"},{"attributeType":"null","col":8,"comment":"null","endLoc":498,"id":506,"name":"_got_first_request","nodeType":"Attribute","startLoc":498,"text":"self._got_first_request"},{"attributeType":"SessionMixin","col":0,"comment":"null","endLoc":56,"id":507,"name":"session","nodeType":"Attribute","startLoc":56,"text":"session"},{"attributeType":"null","col":8,"comment":"null","endLoc":449,"id":508,"name":"teardown_appcontext_funcs","nodeType":"Attribute","startLoc":449,"text":"self.teardown_appcontext_funcs"},{"col":4,"comment":"null","endLoc":113,"header":"def to_python(self, value: t.Any) -> t.Any","id":509,"name":"to_python","nodeType":"Function","startLoc":111,"text":"def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}"},{"attributeType":"null","col":8,"comment":"null","endLoc":494,"id":510,"name":"subdomain_matching","nodeType":"Attribute","startLoc":494,"text":"self.subdomain_matching"},{"attributeType":"null","col":4,"comment":"null","endLoc":97,"id":511,"name":"__slots__","nodeType":"Attribute","startLoc":97,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":98,"id":512,"name":"key","nodeType":"Attribute","startLoc":98,"text":"key"},{"col":0,"comment":"Flashes a message to the next request. In order to remove the\n flashed message from the session and to display it to the user,\n the template has to call :func:`get_flashed_messages`.\n\n .. versionchanged:: 0.3\n `category` parameter added.\n\n :param message: the message to be flashed.\n :param category: the category for the message. The following values\n are recommended: ``'message'`` for any kind of message,\n ``'error'`` for errors, ``'info'`` for information\n messages and ``'warning'`` for warnings. However any\n kind of string can be used as category.\n ","endLoc":393,"header":"def flash(message: str, category: str = \"message\") -> None","id":513,"name":"flash","nodeType":"Function","startLoc":364,"text":"def flash(message: str, category: str = \"message\") -> None:\n \"\"\"Flashes a message to the next request. In order to remove the\n flashed message from the session and to display it to the user,\n the template has to call :func:`get_flashed_messages`.\n\n .. versionchanged:: 0.3\n `category` parameter added.\n\n :param message: the message to be flashed.\n :param category: the category for the message. The following values\n are recommended: ``'message'`` for any kind of message,\n ``'error'`` for errors, ``'info'`` for information\n messages and ``'warning'`` for warnings. However any\n kind of string can be used as category.\n \"\"\"\n # Original implementation:\n #\n # session.setdefault('_flashes', []).append((category, message))\n #\n # This assumed that changes made to mutable structures in the session are\n # always in sync with the session object, which is not true for session\n # implementations that use external storage for keeping their keys/values.\n flashes = session.get(\"_flashes\", [])\n flashes.append((category, message))\n session[\"_flashes\"] = flashes\n message_flashed.send(\n current_app._get_current_object(), # type: ignore\n message=message,\n category=category,\n )"},{"className":"PassDict","col":0,"comment":"null","endLoc":127,"id":514,"nodeType":"Class","startLoc":116,"text":"class PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json"},{"col":4,"comment":"null","endLoc":120,"header":"def check(self, value: t.Any) -> bool","id":515,"name":"check","nodeType":"Function","startLoc":119,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)"},{"col":4,"comment":"null","endLoc":125,"header":"def to_json(self, value: t.Any) -> t.Any","id":516,"name":"to_json","nodeType":"Function","startLoc":122,"text":"def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}"},{"attributeType":"None","col":8,"comment":"null","endLoc":418,"id":517,"name":"instance_path","nodeType":"Attribute","startLoc":418,"text":"self.instance_path"},{"attributeType":"null","col":8,"comment":"null","endLoc":423,"id":518,"name":"config","nodeType":"Attribute","startLoc":423,"text":"self.config"},{"attributeType":"null","col":8,"comment":"null","endLoc":499,"id":519,"name":"_before_request_lock","nodeType":"Attribute","startLoc":499,"text":"self._before_request_lock"},{"className":"JSONEncoder","col":0,"comment":"The default JSON encoder. Handles extra types compared to the\n built-in :class:`json.JSONEncoder`.\n\n - :class:`datetime.datetime` and :class:`datetime.date` are\n serialized to :rfc:`822` strings. This is the same as the HTTP\n date format.\n - :class:`uuid.UUID` is serialized to a string.\n - :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n - :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n\n Assign a subclass of this to :attr:`flask.Flask.json_encoder` or\n :attr:`flask.Blueprint.json_encoder` to override the default.\n ","endLoc":56,"id":520,"nodeType":"Class","startLoc":25,"text":"class JSONEncoder(_json.JSONEncoder):\n \"\"\"The default JSON encoder. Handles extra types compared to the\n built-in :class:`json.JSONEncoder`.\n\n - :class:`datetime.datetime` and :class:`datetime.date` are\n serialized to :rfc:`822` strings. This is the same as the HTTP\n date format.\n - :class:`uuid.UUID` is serialized to a string.\n - :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n - :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n\n Assign a subclass of this to :attr:`flask.Flask.json_encoder` or\n :attr:`flask.Blueprint.json_encoder` to override the default.\n \"\"\"\n\n def default(self, o: t.Any) -> t.Any:\n \"\"\"Convert ``o`` to a JSON serializable type. See\n :meth:`json.JSONEncoder.default`. Python does not support\n overriding how basic types like ``str`` or ``list`` are\n serialized, they are handled before this method.\n \"\"\"\n if isinstance(o, date):\n return http_date(o)\n if isinstance(o, uuid.UUID):\n return str(o)\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o)\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n return super().default(o)"},{"col":4,"comment":"Convert ``o`` to a JSON serializable type. See\n :meth:`json.JSONEncoder.default`. Python does not support\n overriding how basic types like ``str`` or ``list`` are\n serialized, they are handled before this method.\n ","endLoc":56,"header":"def default(self, o: t.Any) -> t.Any","id":521,"name":"default","nodeType":"Function","startLoc":42,"text":"def default(self, o: t.Any) -> t.Any:\n \"\"\"Convert ``o`` to a JSON serializable type. See\n :meth:`json.JSONEncoder.default`. Python does not support\n overriding how basic types like ``str`` or ``list`` are\n serialized, they are handled before this method.\n \"\"\"\n if isinstance(o, date):\n return http_date(o)\n if isinstance(o, uuid.UUID):\n return str(o)\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o)\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n return super().default(o)"},{"attributeType":"null","col":4,"comment":"null","endLoc":117,"id":522,"name":"__slots__","nodeType":"Attribute","startLoc":117,"text":"__slots__"},{"className":"UnexpectedUnicodeError","col":0,"comment":"Raised in places where we want some better error reporting for\n unexpected unicode or binary data.\n ","endLoc":13,"id":523,"nodeType":"Class","startLoc":10,"text":"class UnexpectedUnicodeError(AssertionError, UnicodeError):\n \"\"\"Raised in places where we want some better error reporting for\n unexpected unicode or binary data.\n \"\"\""},{"attributeType":"function","col":4,"comment":"null","endLoc":127,"id":524,"name":"tag","nodeType":"Attribute","startLoc":127,"text":"tag"},{"className":"DebugFilesKeyError","col":0,"comment":"Raised from request.files during debugging. The idea is that it can\n provide a better error message than just a generic KeyError/BadRequest.\n ","endLoc":40,"id":525,"nodeType":"Class","startLoc":16,"text":"class DebugFilesKeyError(KeyError, AssertionError):\n \"\"\"Raised from request.files during debugging. The idea is that it can\n provide a better error message than just a generic KeyError/BadRequest.\n \"\"\"\n\n def __init__(self, request, key):\n form_matches = request.form.getlist(key)\n buf = [\n f\"You tried to access the file {key!r} in the request.files\"\n \" dictionary but it does not exist. The mimetype for the\"\n f\" request is {request.mimetype!r} instead of\"\n \" 'multipart/form-data' which means that no file contents\"\n \" were transmitted. To fix this error you should provide\"\n ' enctype=\"multipart/form-data\" in your form.'\n ]\n if form_matches:\n names = \", \".join(repr(x) for x in form_matches)\n buf.append(\n \"\\n\\nThe browser instead transmitted some file names. \"\n f\"This was submitted: {names}\"\n )\n self.msg = \"\".join(buf)\n\n def __str__(self):\n return self.msg"},{"col":4,"comment":"null","endLoc":40,"header":"def __str__(self)","id":526,"name":"__str__","nodeType":"Function","startLoc":39,"text":"def __str__(self):\n return self.msg"},{"className":"TagTuple","col":0,"comment":"null","endLoc":141,"id":527,"nodeType":"Class","startLoc":130,"text":"class TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)"},{"attributeType":"null","col":8,"comment":"null","endLoc":37,"id":528,"name":"msg","nodeType":"Attribute","startLoc":37,"text":"self.msg"},{"col":4,"comment":"null","endLoc":135,"header":"def check(self, value: t.Any) -> bool","id":529,"name":"check","nodeType":"Function","startLoc":134,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)"},{"col":4,"comment":"null","endLoc":138,"header":"def to_json(self, value: t.Any) -> t.Any","id":530,"name":"to_json","nodeType":"Function","startLoc":137,"text":"def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]"},{"className":"_AppCtxGlobals","col":0,"comment":"A plain object. Used as a namespace for storing data during an\n application context.\n\n Creating an app context automatically creates this object, which is\n made available as the :data:`g` proxy.\n\n .. describe:: 'key' in g\n\n Check whether an attribute is present.\n\n .. versionadded:: 0.10\n\n .. describe:: iter(g)\n\n Return an iterator over the attribute names.\n\n .. versionadded:: 0.10\n ","endLoc":109,"id":531,"nodeType":"Class","startLoc":24,"text":"class _AppCtxGlobals:\n \"\"\"A plain object. Used as a namespace for storing data during an\n application context.\n\n Creating an app context automatically creates this object, which is\n made available as the :data:`g` proxy.\n\n .. describe:: 'key' in g\n\n Check whether an attribute is present.\n\n .. versionadded:: 0.10\n\n .. describe:: iter(g)\n\n Return an iterator over the attribute names.\n\n .. versionadded:: 0.10\n \"\"\"\n\n # Define attr methods to let mypy know this is a namespace object\n # that has arbitrary attributes.\n\n def __getattr__(self, name: str) -> t.Any:\n try:\n return self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None\n\n def __setattr__(self, name: str, value: t.Any) -> None:\n self.__dict__[name] = value\n\n def __delattr__(self, name: str) -> None:\n try:\n del self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None\n\n def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:\n \"\"\"Get an attribute by name, or a default value. Like\n :meth:`dict.get`.\n\n :param name: Name of attribute to get.\n :param default: Value to return if the attribute is not present.\n\n .. versionadded:: 0.10\n \"\"\"\n return self.__dict__.get(name, default)\n\n def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:\n \"\"\"Get and remove an attribute by name. Like :meth:`dict.pop`.\n\n :param name: Name of attribute to pop.\n :param default: Value to return if the attribute is not present,\n instead of raising a ``KeyError``.\n\n .. versionadded:: 0.11\n \"\"\"\n if default is _sentinel:\n return self.__dict__.pop(name)\n else:\n return self.__dict__.pop(name, default)\n\n def setdefault(self, name: str, default: t.Any = None) -> t.Any:\n \"\"\"Get the value of an attribute if it is present, otherwise\n set and return a default value. Like :meth:`dict.setdefault`.\n\n :param name: Name of attribute to get.\n :param default: Value to set and return if the attribute is not\n present.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.__dict__.setdefault(name, default)\n\n def __contains__(self, item: str) -> bool:\n return item in self.__dict__\n\n def __iter__(self) -> t.Iterator[str]:\n return iter(self.__dict__)\n\n def __repr__(self) -> str:\n top = _app_ctx_stack.top\n if top is not None:\n return f\"\"\n return object.__repr__(self)"},{"col":4,"comment":"null","endLoc":51,"header":"def __getattr__(self, name: str) -> t.Any","id":532,"name":"__getattr__","nodeType":"Function","startLoc":47,"text":"def __getattr__(self, name: str) -> t.Any:\n try:\n return self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None"},{"col":4,"comment":"null","endLoc":54,"header":"def __setattr__(self, name: str, value: t.Any) -> None","id":533,"name":"__setattr__","nodeType":"Function","startLoc":53,"text":"def __setattr__(self, name: str, value: t.Any) -> None:\n self.__dict__[name] = value"},{"col":4,"comment":"null","endLoc":60,"header":"def __delattr__(self, name: str) -> None","id":534,"name":"__delattr__","nodeType":"Function","startLoc":56,"text":"def __delattr__(self, name: str) -> None:\n try:\n del self.__dict__[name]\n except KeyError:\n raise AttributeError(name) from None"},{"className":"FormDataRoutingRedirect","col":0,"comment":"This exception is raised by Flask in debug mode if it detects a\n redirect caused by the routing system when the request method is not\n GET, HEAD or OPTIONS. Reasoning: form data will be dropped.\n ","endLoc":72,"id":535,"nodeType":"Class","startLoc":43,"text":"class FormDataRoutingRedirect(AssertionError):\n \"\"\"This exception is raised by Flask in debug mode if it detects a\n redirect caused by the routing system when the request method is not\n GET, HEAD or OPTIONS. Reasoning: form data will be dropped.\n \"\"\"\n\n def __init__(self, request):\n exc = request.routing_exception\n buf = [\n f\"A request was sent to this URL ({request.url}) but a\"\n \" redirect was issued automatically by the routing system\"\n f\" to {exc.new_url!r}.\"\n ]\n\n # In case just a slash was appended we can be extra helpful\n if f\"{request.base_url}/\" == exc.new_url.split(\"?\")[0]:\n buf.append(\n \" The URL was defined with a trailing slash so Flask\"\n \" will automatically redirect to the URL with the\"\n \" trailing slash if it was accessed without one.\"\n )\n\n buf.append(\n \" Make sure to directly send your\"\n f\" {request.method}-request to this URL since we can't make\"\n \" browsers or HTTP clients redirect with form data reliably\"\n \" or without user interaction.\"\n )\n buf.append(\"\\n\\nNote: this exception is only raised in debug mode\")\n AssertionError.__init__(self, \"\".join(buf).encode(\"utf-8\"))"},{"col":0,"comment":"null","endLoc":110,"header":"def _dump_loader_info(loader) -> t.Generator","id":536,"name":"_dump_loader_info","nodeType":"Function","startLoc":96,"text":"def _dump_loader_info(loader) -> t.Generator:\n yield f\"class: {type(loader).__module__}.{type(loader).__name__}\"\n for key, value in sorted(loader.__dict__.items()):\n if key.startswith(\"_\"):\n continue\n if isinstance(value, (tuple, list)):\n if not all(isinstance(x, str) for x in value):\n continue\n yield f\"{key}:\"\n for item in value:\n yield f\" - {item}\"\n continue\n elif not isinstance(value, (str, int, float, bool)):\n continue\n yield f\"{key}: {value!r}\""},{"col":4,"comment":"Get an attribute by name, or a default value. Like\n :meth:`dict.get`.\n\n :param name: Name of attribute to get.\n :param default: Value to return if the attribute is not present.\n\n .. versionadded:: 0.10\n ","endLoc":71,"header":"def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any","id":537,"name":"get","nodeType":"Function","startLoc":62,"text":"def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:\n \"\"\"Get an attribute by name, or a default value. Like\n :meth:`dict.get`.\n\n :param name: Name of attribute to get.\n :param default: Value to return if the attribute is not present.\n\n .. versionadded:: 0.10\n \"\"\"\n return self.__dict__.get(name, default)"},{"col":4,"comment":"Get and remove an attribute by name. Like :meth:`dict.pop`.\n\n :param name: Name of attribute to pop.\n :param default: Value to return if the attribute is not present,\n instead of raising a ``KeyError``.\n\n .. versionadded:: 0.11\n ","endLoc":85,"header":"def pop(self, name: str, default: t.Any = _sentinel) -> t.Any","id":538,"name":"pop","nodeType":"Function","startLoc":73,"text":"def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:\n \"\"\"Get and remove an attribute by name. Like :meth:`dict.pop`.\n\n :param name: Name of attribute to pop.\n :param default: Value to return if the attribute is not present,\n instead of raising a ``KeyError``.\n\n .. versionadded:: 0.11\n \"\"\"\n if default is _sentinel:\n return self.__dict__.pop(name)\n else:\n return self.__dict__.pop(name, default)"},{"col":4,"comment":"null","endLoc":141,"header":"def to_python(self, value: t.Any) -> t.Any","id":539,"name":"to_python","nodeType":"Function","startLoc":140,"text":"def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)"},{"attributeType":"null","col":4,"comment":"null","endLoc":131,"id":540,"name":"__slots__","nodeType":"Attribute","startLoc":131,"text":"__slots__"},{"className":"Environment","col":0,"comment":"Works like a regular Jinja2 environment but has some additional\n knowledge of how Flask's blueprint works so that it can prepend the\n name of the blueprint to referenced templates if necessary.\n ","endLoc":43,"id":541,"nodeType":"Class","startLoc":33,"text":"class Environment(BaseEnvironment):\n \"\"\"Works like a regular Jinja2 environment but has some additional\n knowledge of how Flask's blueprint works so that it can prepend the\n name of the blueprint to referenced templates if necessary.\n \"\"\"\n\n def __init__(self, app: \"Flask\", **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app"},{"attributeType":"null","col":4,"comment":"null","endLoc":132,"id":542,"name":"key","nodeType":"Attribute","startLoc":132,"text":"key"},{"className":"PassList","col":0,"comment":"null","endLoc":153,"id":543,"nodeType":"Class","startLoc":144,"text":"class PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json"},{"col":4,"comment":"null","endLoc":148,"header":"def check(self, value: t.Any) -> bool","id":544,"name":"check","nodeType":"Function","startLoc":147,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, list)"},{"col":4,"comment":"null","endLoc":43,"header":"def __init__(self, app: \"Flask\", **options: t.Any) -> None","id":545,"name":"__init__","nodeType":"Function","startLoc":39,"text":"def __init__(self, app: \"Flask\", **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app"},{"col":4,"comment":"null","endLoc":151,"header":"def to_json(self, value: t.Any) -> t.Any","id":546,"name":"to_json","nodeType":"Function","startLoc":150,"text":"def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]"},{"col":4,"comment":"Get the value of an attribute if it is present, otherwise\n set and return a default value. Like :meth:`dict.setdefault`.\n\n :param name: Name of attribute to get.\n :param default: Value to set and return if the attribute is not\n present.\n\n .. versionadded:: 0.11\n ","endLoc":97,"header":"def setdefault(self, name: str, default: t.Any = None) -> t.Any","id":547,"name":"setdefault","nodeType":"Function","startLoc":87,"text":"def setdefault(self, name: str, default: t.Any = None) -> t.Any:\n \"\"\"Get the value of an attribute if it is present, otherwise\n set and return a default value. Like :meth:`dict.setdefault`.\n\n :param name: Name of attribute to get.\n :param default: Value to set and return if the attribute is not\n present.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.__dict__.setdefault(name, default)"},{"col":4,"comment":"null","endLoc":100,"header":"def __contains__(self, item: str) -> bool","id":548,"name":"__contains__","nodeType":"Function","startLoc":99,"text":"def __contains__(self, item: str) -> bool:\n return item in self.__dict__"},{"col":4,"comment":"null","endLoc":103,"header":"def __iter__(self) -> t.Iterator[str]","id":549,"name":"__iter__","nodeType":"Function","startLoc":102,"text":"def __iter__(self) -> t.Iterator[str]:\n return iter(self.__dict__)"},{"col":4,"comment":"null","endLoc":109,"header":"def __repr__(self) -> str","id":550,"name":"__repr__","nodeType":"Function","startLoc":105,"text":"def __repr__(self) -> str:\n top = _app_ctx_stack.top\n if top is not None:\n return f\"\"\n return object.__repr__(self)"},{"className":"AppContext","col":0,"comment":"The application context binds an application object implicitly\n to the current thread or greenlet, similar to how the\n :class:`RequestContext` binds request information. The application\n context is also implicitly created if a request context is created\n but the application is not on top of the individual application\n context.\n ","endLoc":263,"id":551,"nodeType":"Class","startLoc":219,"text":"class AppContext:\n \"\"\"The application context binds an application object implicitly\n to the current thread or greenlet, similar to how the\n :class:`RequestContext` binds request information. The application\n context is also implicitly created if a request context is created\n but the application is not on top of the individual application\n context.\n \"\"\"\n\n def __init__(self, app: \"Flask\") -> None:\n self.app = app\n self.url_adapter = app.create_url_adapter(None)\n self.g = app.app_ctx_globals_class()\n\n # Like request context, app contexts can be pushed multiple times\n # but there a basic \"refcount\" is enough to track them.\n self._refcnt = 0\n\n def push(self) -> None:\n \"\"\"Binds the app context to the current context.\"\"\"\n self._refcnt += 1\n _app_ctx_stack.push(self)\n appcontext_pushed.send(self.app)\n\n def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore\n \"\"\"Pops the app context.\"\"\"\n try:\n self._refcnt -= 1\n if self._refcnt <= 0:\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n self.app.do_teardown_appcontext(exc)\n finally:\n rv = _app_ctx_stack.pop()\n assert rv is self, f\"Popped wrong app context. ({rv!r} instead of {self!r})\"\n appcontext_popped.send(self.app)\n\n def __enter__(self) -> \"AppContext\":\n self.push()\n return self\n\n def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n self.pop(exc_value)"},{"col":4,"comment":"Binds the app context to the current context.","endLoc":241,"header":"def push(self) -> None","id":552,"name":"push","nodeType":"Function","startLoc":237,"text":"def push(self) -> None:\n \"\"\"Binds the app context to the current context.\"\"\"\n self._refcnt += 1\n _app_ctx_stack.push(self)\n appcontext_pushed.send(self.app)"},{"attributeType":"null","col":4,"comment":"null","endLoc":145,"id":553,"name":"__slots__","nodeType":"Attribute","startLoc":145,"text":"__slots__"},{"attributeType":"function","col":4,"comment":"null","endLoc":153,"id":554,"name":"tag","nodeType":"Attribute","startLoc":153,"text":"tag"},{"className":"TagBytes","col":0,"comment":"null","endLoc":167,"id":555,"nodeType":"Class","startLoc":156,"text":"class TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)"},{"col":4,"comment":"Pops the app context.","endLoc":254,"header":"def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None","id":556,"name":"pop","nodeType":"Function","startLoc":243,"text":"def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore\n \"\"\"Pops the app context.\"\"\"\n try:\n self._refcnt -= 1\n if self._refcnt <= 0:\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n self.app.do_teardown_appcontext(exc)\n finally:\n rv = _app_ctx_stack.pop()\n assert rv is self, f\"Popped wrong app context. ({rv!r} instead of {self!r})\"\n appcontext_popped.send(self.app)"},{"col":4,"comment":"null","endLoc":161,"header":"def check(self, value: t.Any) -> bool","id":557,"name":"check","nodeType":"Function","startLoc":160,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)"},{"col":4,"comment":"null","endLoc":164,"header":"def to_json(self, value: t.Any) -> t.Any","id":558,"name":"to_json","nodeType":"Function","startLoc":163,"text":"def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")"},{"className":"JSONDecoder","col":0,"comment":"The default JSON decoder.\n\n This does not change any behavior from the built-in\n :class:`json.JSONDecoder`.\n\n Assign a subclass of this to :attr:`flask.Flask.json_decoder` or\n :attr:`flask.Blueprint.json_decoder` to override the default.\n ","endLoc":67,"id":559,"nodeType":"Class","startLoc":59,"text":"class JSONDecoder(_json.JSONDecoder):\n \"\"\"The default JSON decoder.\n\n This does not change any behavior from the built-in\n :class:`json.JSONDecoder`.\n\n Assign a subclass of this to :attr:`flask.Flask.json_decoder` or\n :attr:`flask.Blueprint.json_decoder` to override the default.\n \"\"\""},{"col":4,"comment":"null","endLoc":167,"header":"def to_python(self, value: t.Any) -> t.Any","id":560,"name":"to_python","nodeType":"Function","startLoc":166,"text":"def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)"},{"col":0,"comment":"Serialize an object to JSON written to a file object.\n\n Takes the same arguments as the built-in :func:`json.dump`, with\n some defaults from application configuration.\n\n :param obj: Object to serialize to JSON.\n :param fp: File object to write JSON to.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.dump`.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, is\n deprecated and will be removed in Flask 2.1.\n ","endLoc":180,"header":"def dump(\n obj: t.Any, fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any\n) -> None","id":561,"name":"dump","nodeType":"Function","startLoc":144,"text":"def dump(\n obj: t.Any, fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any\n) -> None:\n \"\"\"Serialize an object to JSON written to a file object.\n\n Takes the same arguments as the built-in :func:`json.dump`, with\n some defaults from application configuration.\n\n :param obj: Object to serialize to JSON.\n :param fp: File object to write JSON to.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.dump`.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, is\n deprecated and will be removed in Flask 2.1.\n \"\"\"\n _dump_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n show_warning = encoding is not None\n\n try:\n fp.write(\"\")\n except TypeError:\n show_warning = True\n fp = io.TextIOWrapper(fp, encoding or \"utf-8\") # type: ignore\n\n if show_warning:\n warnings.warn(\n \"Writing to a binary file, and the 'encoding' argument, is\"\n \" deprecated and will be removed in Flask 2.1.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n _json.dump(obj, fp, **kwargs)"},{"attributeType":"null","col":4,"comment":"null","endLoc":157,"id":562,"name":"__slots__","nodeType":"Attribute","startLoc":157,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":158,"id":563,"name":"key","nodeType":"Attribute","startLoc":158,"text":"key"},{"className":"TagMarkup","col":0,"comment":"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.","endLoc":185,"id":564,"nodeType":"Class","startLoc":170,"text":"class TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)"},{"col":4,"comment":"null","endLoc":179,"header":"def check(self, value: t.Any) -> bool","id":565,"name":"check","nodeType":"Function","startLoc":178,"text":"def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))"},{"col":0,"comment":"Pulls all flashed messages from the session and returns them.\n Further calls in the same request to the function will return\n the same messages. By default just the messages are returned,\n but when `with_categories` is set to ``True``, the return value will\n be a list of tuples in the form ``(category, message)`` instead.\n\n Filter the flashed messages to one or more categories by providing those\n categories in `category_filter`. This allows rendering categories in\n separate html blocks. The `with_categories` and `category_filter`\n arguments are distinct:\n\n * `with_categories` controls whether categories are returned with message\n text (``True`` gives a tuple, where ``False`` gives just the message text).\n * `category_filter` filters the messages down to only those matching the\n provided categories.\n\n See :doc:`/patterns/flashing` for examples.\n\n .. versionchanged:: 0.3\n `with_categories` parameter added.\n\n .. versionchanged:: 0.9\n `category_filter` parameter added.\n\n :param with_categories: set to ``True`` to also receive categories.\n :param category_filter: filter of categories to limit return values. Only\n categories in the list will be returned.\n ","endLoc":436,"header":"def get_flashed_messages(\n with_categories: bool = False, category_filter: t.Iterable[str] = ()\n) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]","id":566,"name":"get_flashed_messages","nodeType":"Function","startLoc":396,"text":"def get_flashed_messages(\n with_categories: bool = False, category_filter: t.Iterable[str] = ()\n) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:\n \"\"\"Pulls all flashed messages from the session and returns them.\n Further calls in the same request to the function will return\n the same messages. By default just the messages are returned,\n but when `with_categories` is set to ``True``, the return value will\n be a list of tuples in the form ``(category, message)`` instead.\n\n Filter the flashed messages to one or more categories by providing those\n categories in `category_filter`. This allows rendering categories in\n separate html blocks. The `with_categories` and `category_filter`\n arguments are distinct:\n\n * `with_categories` controls whether categories are returned with message\n text (``True`` gives a tuple, where ``False`` gives just the message text).\n * `category_filter` filters the messages down to only those matching the\n provided categories.\n\n See :doc:`/patterns/flashing` for examples.\n\n .. versionchanged:: 0.3\n `with_categories` parameter added.\n\n .. versionchanged:: 0.9\n `category_filter` parameter added.\n\n :param with_categories: set to ``True`` to also receive categories.\n :param category_filter: filter of categories to limit return values. Only\n categories in the list will be returned.\n \"\"\"\n flashes = _request_ctx_stack.top.flashes\n if flashes is None:\n _request_ctx_stack.top.flashes = flashes = (\n session.pop(\"_flashes\") if \"_flashes\" in session else []\n )\n if category_filter:\n flashes = list(filter(lambda f: f[0] in category_filter, flashes))\n if not with_categories:\n return [x[1] for x in flashes]\n return flashes"},{"col":4,"comment":"null","endLoc":182,"header":"def to_json(self, value: t.Any) -> t.Any","id":567,"name":"to_json","nodeType":"Function","startLoc":181,"text":"def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())"},{"col":4,"comment":"null","endLoc":185,"header":"def to_python(self, value: t.Any) -> t.Any","id":568,"name":"to_python","nodeType":"Function","startLoc":184,"text":"def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)"},{"col":30,"endLoc":433,"id":569,"nodeType":"Lambda","startLoc":433,"text":"lambda f: f[0] in category_filter"},{"attributeType":"null","col":4,"comment":"null","endLoc":175,"id":570,"name":"__slots__","nodeType":"Attribute","startLoc":175,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":176,"id":571,"name":"key","nodeType":"Attribute","startLoc":176,"text":"key"},{"col":0,"comment":"Loads a macro (or variable) a template exports. This can be used to\n invoke a macro from within Python code. If you for example have a\n template named :file:`_cider.html` with the following contents:\n\n .. sourcecode:: html+jinja\n\n {% macro hello(name) %}Hello {{ name }}!{% endmacro %}\n\n You can access this from Python code like this::\n\n hello = get_template_attribute('_cider.html', 'hello')\n return hello('World')\n\n .. versionadded:: 0.2\n\n :param template_name: the name of the template\n :param attribute: the name of the variable of macro to access\n ","endLoc":361,"header":"def get_template_attribute(template_name: str, attribute: str) -> t.Any","id":572,"name":"get_template_attribute","nodeType":"Function","startLoc":342,"text":"def get_template_attribute(template_name: str, attribute: str) -> t.Any:\n \"\"\"Loads a macro (or variable) a template exports. This can be used to\n invoke a macro from within Python code. If you for example have a\n template named :file:`_cider.html` with the following contents:\n\n .. sourcecode:: html+jinja\n\n {% macro hello(name) %}Hello {{ name }}!{% endmacro %}\n\n You can access this from Python code like this::\n\n hello = get_template_attribute('_cider.html', 'hello')\n return hello('World')\n\n .. versionadded:: 0.2\n\n :param template_name: the name of the template\n :param attribute: the name of the variable of macro to access\n \"\"\"\n return getattr(current_app.jinja_env.get_template(template_name).module, attribute)"},{"className":"TagUUID","col":0,"comment":"null","endLoc":199,"id":573,"nodeType":"Class","startLoc":188,"text":"class TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) -> t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)"},{"col":4,"comment":"null","endLoc":193,"header":"def check(self, value: t.Any) -> bool","id":574,"name":"check","nodeType":"Function","startLoc":192,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)"},{"col":4,"comment":"null","endLoc":196,"header":"def to_json(self, value: t.Any) -> t.Any","id":575,"name":"to_json","nodeType":"Function","startLoc":195,"text":"def to_json(self, value: t.Any) -> t.Any:\n return value.hex"},{"col":4,"comment":"null","endLoc":199,"header":"def to_python(self, value: t.Any) -> t.Any","id":576,"name":"to_python","nodeType":"Function","startLoc":198,"text":"def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)"},{"col":0,"comment":"Deserialize an object from JSON read from a file object.\n\n Takes the same arguments as the built-in :func:`json.load`, with\n some defaults from application configuration.\n\n :param fp: File object to read JSON from.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.load`.\n\n .. versionchanged:: 2.0\n ``encoding`` is deprecated and will be removed in Flask 2.1. The\n file must be text mode, or binary mode with UTF-8 bytes.\n ","endLoc":249,"header":"def load(fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any) -> t.Any","id":577,"name":"load","nodeType":"Function","startLoc":219,"text":"def load(fp: t.IO[str], app: t.Optional[\"Flask\"] = None, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize an object from JSON read from a file object.\n\n Takes the same arguments as the built-in :func:`json.load`, with\n some defaults from application configuration.\n\n :param fp: File object to read JSON from.\n :param app: Use this app's config instead of the active app context\n or defaults.\n :param kwargs: Extra arguments passed to :func:`json.load`.\n\n .. versionchanged:: 2.0\n ``encoding`` is deprecated and will be removed in Flask 2.1. The\n file must be text mode, or binary mode with UTF-8 bytes.\n \"\"\"\n _load_arg_defaults(kwargs, app=app)\n encoding = kwargs.pop(\"encoding\", None)\n\n if encoding is not None:\n warnings.warn(\n \"'encoding' is deprecated and will be removed in Flask 2.1.\"\n \" The file must be text mode, or binary mode with UTF-8\"\n \" bytes.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n if isinstance(fp.read(0), bytes):\n fp = io.TextIOWrapper(fp, encoding) # type: ignore\n\n return _json.load(fp, **kwargs)"},{"attributeType":"null","col":4,"comment":"null","endLoc":189,"id":578,"name":"__slots__","nodeType":"Attribute","startLoc":189,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":190,"id":579,"name":"key","nodeType":"Attribute","startLoc":190,"text":"key"},{"className":"TagDateTime","col":0,"comment":"null","endLoc":213,"id":580,"nodeType":"Class","startLoc":202,"text":"class TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)"},{"col":4,"comment":"null","endLoc":207,"header":"def check(self, value: t.Any) -> bool","id":581,"name":"check","nodeType":"Function","startLoc":206,"text":"def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)"},{"col":4,"comment":"null","endLoc":210,"header":"def to_json(self, value: t.Any) -> t.Any","id":582,"name":"to_json","nodeType":"Function","startLoc":209,"text":"def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)"},{"col":4,"comment":"null","endLoc":213,"header":"def to_python(self, value: t.Any) -> t.Any","id":583,"name":"to_python","nodeType":"Function","startLoc":212,"text":"def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)"},{"attributeType":"null","col":4,"comment":"null","endLoc":203,"id":584,"name":"__slots__","nodeType":"Attribute","startLoc":203,"text":"__slots__"},{"attributeType":"null","col":4,"comment":"null","endLoc":204,"id":585,"name":"key","nodeType":"Attribute","startLoc":204,"text":"key"},{"col":0,"comment":"","endLoc":42,"header":"tag.py#","id":586,"name":"","nodeType":"Function","startLoc":1,"text":"\"\"\"\nTagged JSON\n~~~~~~~~~~~\n\nA compact representation for lossless serialization of non-standard JSON\ntypes. :class:`~flask.sessions.SecureCookieSessionInterface` uses this\nto serialize the session data, but it may be useful in other places. It\ncan be extended to support other types.\n\n.. autoclass:: TaggedJSONSerializer\n :members:\n\n.. autoclass:: JSONTag\n :members:\n\nLet's see an example that adds support for\n:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so\nto handle this we will dump the items as a list of ``[key, value]``\npairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to\nidentify the type. The session serializer processes dicts first, so\ninsert the new tag at the front of the order since ``OrderedDict`` must\nbe processed before ``dict``.\n\n.. code-block:: python\n\n from flask.json.tag import JSONTag\n\n class TagOrderedDict(JSONTag):\n __slots__ = ('serializer',)\n key = ' od'\n\n def check(self, value):\n return isinstance(value, OrderedDict)\n\n def to_json(self, value):\n return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]\n\n def to_python(self, value):\n return OrderedDict(value)\n\n app.session_interface.serializer.register(TagOrderedDict, index=0)\n\"\"\""},{"id":587,"name":"extensions.rst","nodeType":"TextFile","path":"docs","text":"Extensions\n==========\n\nExtensions are extra packages that add functionality to a Flask\napplication. For example, an extension might add support for sending\nemail or connecting to a database. Some extensions add entire new\nframeworks to help build certain types of applications, like a REST API.\n\n\nFinding Extensions\n------------------\n\nFlask extensions are usually named \"Flask-Foo\" or \"Foo-Flask\". You can\nsearch PyPI for packages tagged with `Framework :: Flask `_.\n\n\nUsing Extensions\n----------------\n\nConsult each extension's documentation for installation, configuration,\nand usage instructions. Generally, extensions pull their own\nconfiguration from :attr:`app.config ` and are\npassed an application instance during initialization. For example,\nan extension called \"Flask-Foo\" might be used like this::\n\n from flask_foo import Foo\n\n foo = Foo()\n\n app = Flask(__name__)\n app.config.update(\n FOO_BAR='baz',\n FOO_SPAM='eggs',\n )\n\n foo.init_app(app)\n\n\nBuilding Extensions\n-------------------\n\nWhile the `PyPI `_ contains many Flask extensions, you may\nnot find an extension that fits your need. If this is the case, you can\ncreate your own. Read :doc:`/extensiondev` to develop your own Flask\nextension.\n\n\n.. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask\n"},{"id":588,"name":"async-await.rst","nodeType":"TextFile","path":"docs","text":".. _async_await:\n\nUsing ``async`` and ``await``\n=============================\n\n.. versionadded:: 2.0\n\nRoutes, error handlers, before request, after request, and teardown\nfunctions can all be coroutine functions if Flask is installed with the\n``async`` extra (``pip install flask[async]``). This allows views to be\ndefined with ``async def`` and use ``await``.\n\n.. code-block:: python\n\n @app.route(\"/get-data\")\n async def get_data():\n data = await async_db_query(...)\n return jsonify(data)\n\n.. admonition:: Using ``async`` on Windows on Python 3.8\n\n Python 3.8 has a bug related to asyncio on Windows. If you encounter\n something like ``ValueError: set_wakeup_fd only works in main thread``,\n please upgrade to Python 3.9.\n\n\nPerformance\n-----------\n\nAsync functions require an event loop to run. Flask, as a WSGI\napplication, uses one worker to handle one request/response cycle.\nWhen a request comes in to an async view, Flask will start an event loop\nin a thread, run the view function there, then return the result.\n\nEach request still ties up one worker, even for async views. The upside\nis that you can run async code within a view, for example to make\nmultiple concurrent database queries, HTTP requests to an external API,\netc. However, the number of requests your application can handle at one\ntime will remain the same.\n\n**Async is not inherently faster than sync code.** Async is beneficial\nwhen performing concurrent IO-bound tasks, but will probably not improve\nCPU-bound tasks. Traditional Flask views will still be appropriate for\nmost use cases, but Flask's async support enables writing and using\ncode that wasn't possible natively before.\n\n\nBackground tasks\n----------------\n\nAsync functions will run in an event loop until they complete, at\nwhich stage the event loop will stop. This means any additional\nspawned tasks that haven't completed when the async function completes\nwill be cancelled. Therefore you cannot spawn background tasks, for\nexample via ``asyncio.create_task``.\n\nIf you wish to use background tasks it is best to use a task queue to\ntrigger background work, rather than spawn tasks in a view\nfunction. With that in mind you can spawn asyncio tasks by serving\nFlask with an ASGI server and utilising the asgiref WsgiToAsgi adapter\nas described in :ref:`asgi`. This works as the adapter creates an\nevent loop that runs continually.\n\n\nWhen to use Quart instead\n-------------------------\n\nFlask's async support is less performant than async-first frameworks due\nto the way it is implemented. If you have a mainly async codebase it\nwould make sense to consider `Quart`_. Quart is a reimplementation of\nFlask based on the `ASGI`_ standard instead of WSGI. This allows it to\nhandle many concurrent requests, long running requests, and websockets\nwithout requiring multiple worker processes or threads.\n\nIt has also already been possible to run Flask with Gevent or Eventlet\nto get many of the benefits of async request handling. These libraries\npatch low-level Python functions to accomplish this, whereas ``async``/\n``await`` and ASGI use standard, modern Python capabilities. Deciding\nwhether you should use Flask, Quart, or something else is ultimately up\nto understanding the specific needs of your project.\n\n.. _Quart: https://gitlab.com/pgjones/quart\n.. _ASGI: https://asgi.readthedocs.io/en/latest/\n\n\nExtensions\n----------\n\nFlask extensions predating Flask's async support do not expect async views.\nIf they provide decorators to add functionality to views, those will probably\nnot work with async views because they will not await the function or be\nawaitable. Other functions they provide will not be awaitable either and\nwill probably be blocking if called within an async view.\n\nExtension authors can support async functions by utilising the\n:meth:`flask.Flask.ensure_sync` method. For example, if the extension\nprovides a view function decorator add ``ensure_sync`` before calling\nthe decorated function,\n\n.. code-block:: python\n\n def extension(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n ... # Extension logic\n return current_app.ensure_sync(func)(*args, **kwargs)\n\n return wrapper\n\nCheck the changelog of the extension you want to use to see if they've\nimplemented async support, or make a feature request or PR to them.\n\n\nOther event loops\n-----------------\n\nAt the moment Flask only supports :mod:`asyncio`. It's possible to\noverride :meth:`flask.Flask.ensure_sync` to change how async functions\nare wrapped to use a different library.\n"},{"fileName":"conf.py","filePath":"docs","id":589,"nodeType":"File","text":"import packaging.version\nfrom pallets_sphinx_themes import get_version\nfrom pallets_sphinx_themes import ProjectLink\n\n# Project --------------------------------------------------------------\n\nproject = \"Flask\"\ncopyright = \"2010 Pallets\"\nauthor = \"Pallets\"\nrelease, version = get_version(\"Flask\")\n\n# General --------------------------------------------------------------\n\nmaster_doc = \"index\"\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.intersphinx\",\n \"sphinxcontrib.log_cabinet\",\n \"pallets_sphinx_themes\",\n \"sphinx_issues\",\n \"sphinx_tabs.tabs\",\n]\nautodoc_typehints = \"description\"\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3/\", None),\n \"werkzeug\": (\"https://werkzeug.palletsprojects.com/\", None),\n \"click\": (\"https://click.palletsprojects.com/\", None),\n \"jinja\": (\"https://jinja.palletsprojects.com/\", None),\n \"itsdangerous\": (\"https://itsdangerous.palletsprojects.com/\", None),\n \"sqlalchemy\": (\"https://docs.sqlalchemy.org/\", None),\n \"wtforms\": (\"https://wtforms.readthedocs.io/\", None),\n \"blinker\": (\"https://pythonhosted.org/blinker/\", None),\n}\nissues_github_path = \"pallets/flask\"\n\n# HTML -----------------------------------------------------------------\n\nhtml_theme = \"flask\"\nhtml_theme_options = {\"index_sidebar_logo\": False}\nhtml_context = {\n \"project_links\": [\n ProjectLink(\"Donate\", \"https://palletsprojects.com/donate\"),\n ProjectLink(\"PyPI Releases\", \"https://pypi.org/project/Flask/\"),\n ProjectLink(\"Source Code\", \"https://github.com/pallets/flask/\"),\n ProjectLink(\"Issue Tracker\", \"https://github.com/pallets/flask/issues/\"),\n ProjectLink(\"Website\", \"https://palletsprojects.com/p/flask/\"),\n ProjectLink(\"Twitter\", \"https://twitter.com/PalletsTeam\"),\n ProjectLink(\"Chat\", \"https://discord.gg/pallets\"),\n ]\n}\nhtml_sidebars = {\n \"index\": [\"project.html\", \"localtoc.html\", \"searchbox.html\"],\n \"**\": [\"localtoc.html\", \"relations.html\", \"searchbox.html\"],\n}\nsinglehtml_sidebars = {\"index\": [\"project.html\", \"localtoc.html\"]}\nhtml_static_path = [\"_static\"]\nhtml_favicon = \"_static/flask-icon.png\"\nhtml_logo = \"_static/flask-icon.png\"\nhtml_title = f\"Flask Documentation ({version})\"\nhtml_show_sourcelink = False\n\n# LaTeX ----------------------------------------------------------------\n\nlatex_documents = [(master_doc, f\"Flask-{version}.tex\", html_title, author, \"manual\")]\n\n# Local Extensions -----------------------------------------------------\n\n\ndef github_link(name, rawtext, text, lineno, inliner, options=None, content=None):\n app = inliner.document.settings.env.app\n release = app.config.release\n base_url = \"https://github.com/pallets/flask/tree/\"\n\n if text.endswith(\">\"):\n words, text = text[:-1].rsplit(\"<\", 1)\n words = words.strip()\n else:\n words = None\n\n if packaging.version.parse(release).is_devrelease:\n url = f\"{base_url}main/{text}\"\n else:\n url = f\"{base_url}{release}/{text}\"\n\n if words is None:\n words = url\n\n from docutils.nodes import reference\n from docutils.parsers.rst.roles import set_classes\n\n options = options or {}\n set_classes(options)\n node = reference(rawtext, words, refuri=url, **options)\n return [node], []\n\n\ndef setup(app):\n app.add_role(\"gh\", github_link)\n"},{"col":0,"comment":"Serialize an object to a string of JSON with :func:`dumps`, then\n replace HTML-unsafe characters with Unicode escapes and mark the\n result safe with :class:`~markupsafe.Markup`.\n\n This is available in templates as the ``|tojson`` filter.\n\n The returned string is safe to render in HTML documents and\n ``\n\nAnother method is using Google's `AJAX Libraries API\n`_ to load jQuery:\n\n.. sourcecode:: html\n\n \n \n\nIn this case you have to put jQuery into your static folder as a fallback, but it will\nfirst try to load it directly from Google. This has the advantage that your\nwebsite will probably load faster for users if they went to at least one\nother website before using the same jQuery version from Google because it\nwill already be in the browser cache.\n\nWhere is My Site?\n-----------------\n\nDo you know where your application is? If you are developing the answer\nis quite simple: it's on localhost port something and directly on the root\nof that server. But what if you later decide to move your application to\na different location? For example to ``http://example.com/myapp``? On\nthe server side this never was a problem because we were using the handy\n:func:`~flask.url_for` function that could answer that question for\nus, but if we are using jQuery we should not hardcode the path to\nthe application but make that dynamic, so how can we do that?\n\nA simple method would be to add a script tag to our page that sets a\nglobal variable to the prefix to the root of the application. Something\nlike this:\n\n.. sourcecode:: html+jinja\n\n \n\n\nJSON View Functions\n-------------------\n\nNow let's create a server side function that accepts two URL arguments of\nnumbers which should be added together and then sent back to the\napplication in a JSON object. This is a really ridiculous example and is\nsomething you usually would do on the client side alone, but a simple\nexample that shows how you would use jQuery and Flask nonetheless::\n\n from flask import Flask, jsonify, render_template, request\n app = Flask(__name__)\n\n @app.route('/_add_numbers')\n def add_numbers():\n a = request.args.get('a', 0, type=int)\n b = request.args.get('b', 0, type=int)\n return jsonify(result=a + b)\n\n @app.route('/')\n def index():\n return render_template('index.html')\n\nAs you can see I also added an `index` method here that renders a\ntemplate. This template will load jQuery as above and have a little form where\nwe can add two numbers and a link to trigger the function on the server\nside.\n\nNote that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here\nwhich will never fail. If the key is missing a default value (here ``0``)\nis returned. Furthermore it can convert values to a specific type (like\nin our case `int`). This is especially handy for code that is\ntriggered by a script (APIs, JavaScript etc.) because you don't need\nspecial error reporting in that case.\n\nThe HTML\n--------\n\nYour index.html template either has to extend a :file:`layout.html` template with\njQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.\nHere's the HTML code needed for our little application (:file:`index.html`).\nNotice that we also drop the script directly into the HTML here. It is\nusually a better idea to have that in a separate script file:\n\n.. sourcecode:: html\n\n \n

jQuery Example

\n

+\n =\n ?\n

calculate server side\n\nI won't go into detail here about how jQuery works, just a very quick\nexplanation of the little bit of code above:\n\n1. ``$(function() { ... })`` specifies code that should run once the\n browser is done loading the basic parts of the page.\n2. ``$('selector')`` selects an element and lets you operate on it.\n3. ``element.bind('event', func)`` specifies a function that should run\n when the user clicked on the element. If that function returns\n `false`, the default behavior will not kick in (in this case, navigate\n to the `#` URL).\n4. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will\n send the contents of the `data` object as query parameters. Once the\n data arrived, it will call the given function with the return value as\n argument. Note that we can use the `$SCRIPT_ROOT` variable here that\n we set earlier.\n\nCheck out the :gh:`example source ` for a full\napplication demonstrating the code on this page, as well as the same\nthing using ``XMLHttpRequest`` and ``fetch``.\n"},{"id":728,"name":"examples/javascript/tests","nodeType":"Package"},{"fileName":"conftest.py","filePath":"examples/javascript/tests","id":729,"nodeType":"File","text":"import pytest\n\nfrom js_example import app\n\n\n@pytest.fixture(name=\"app\")\ndef fixture_app():\n app.testing = True\n yield app\n app.testing = False\n\n\n@pytest.fixture\ndef client(app):\n return app.test_client()\n"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":229,"id":730,"name":"app","nodeType":"Attribute","startLoc":229,"text":"self.app"},{"col":0,"comment":"null","endLoc":10,"header":"@pytest.fixture(name=\"app\")\ndef fixture_app()","id":731,"name":"fixture_app","nodeType":"Function","startLoc":6,"text":"@pytest.fixture(name=\"app\")\ndef fixture_app():\n app.testing = True\n yield app\n app.testing = False"},{"attributeType":"null","col":8,"comment":"null","endLoc":235,"id":732,"name":"_refcnt","nodeType":"Attribute","startLoc":235,"text":"self._refcnt"},{"attributeType":"null","col":8,"comment":"null","endLoc":231,"id":733,"name":"g","nodeType":"Attribute","startLoc":231,"text":"self.g"},{"col":0,"comment":"null","endLoc":15,"header":"@pytest.fixture\ndef client(app)","id":734,"name":"client","nodeType":"Function","startLoc":13,"text":"@pytest.fixture\ndef client(app):\n return app.test_client()"},{"id":735,"name":"celery.rst","nodeType":"TextFile","path":"docs/patterns","text":"Celery Background Tasks\n=======================\n\nIf your application has a long running task, such as processing some uploaded\ndata or sending email, you don't want to wait for it to finish during a\nrequest. Instead, use a task queue to send the necessary data to another\nprocess that will run the task in the background while the request returns\nimmediately.\n\nCelery is a powerful task queue that can be used for simple background tasks\nas well as complex multi-stage programs and schedules. This guide will show you\nhow to configure Celery using Flask, but assumes you've already read the\n`First Steps with Celery `_\nguide in the Celery documentation.\n\nInstall\n-------\n\nCelery is a separate Python package. Install it from PyPI using pip::\n\n $ pip install celery\n\nConfigure\n---------\n\nThe first thing you need is a Celery instance, this is called the celery\napplication. It serves the same purpose as the :class:`~flask.Flask`\nobject in Flask, just for Celery. Since this instance is used as the\nentry-point for everything you want to do in Celery, like creating tasks\nand managing workers, it must be possible for other modules to import it.\n\nFor instance you can place this in a ``tasks`` module. While you can use\nCelery without any reconfiguration with Flask, it becomes a bit nicer by\nsubclassing tasks and adding support for Flask's application contexts and\nhooking it up with the Flask configuration.\n\nThis is all that is necessary to properly integrate Celery with Flask::\n\n from celery import Celery\n\n def make_celery(app):\n celery = Celery(\n app.import_name,\n backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL']\n )\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n return celery\n\nThe function creates a new Celery object, configures it with the broker\nfrom the application config, updates the rest of the Celery config from\nthe Flask config and then creates a subclass of the task that wraps the\ntask execution in an application context.\n\nAn example task\n---------------\n\nLet's write a task that adds two numbers together and returns the result. We\nconfigure Celery's broker and backend to use Redis, create a ``celery``\napplication using the factor from above, and then use it to define the task. ::\n\n from flask import Flask\n\n flask_app = Flask(__name__)\n flask_app.config.update(\n CELERY_BROKER_URL='redis://localhost:6379',\n CELERY_RESULT_BACKEND='redis://localhost:6379'\n )\n celery = make_celery(flask_app)\n\n @celery.task()\n def add_together(a, b):\n return a + b\n\nThis task can now be called in the background::\n\n result = add_together.delay(23, 42)\n result.wait() # 65\n\nRun a worker\n------------\n\nIf you jumped in and already executed the above code you will be\ndisappointed to learn that ``.wait()`` will never actually return.\nThat's because you also need to run a Celery worker to receive and execute the\ntask. ::\n\n $ celery -A your_application.celery worker\n\nThe ``your_application`` string has to point to your application's package\nor module that creates the ``celery`` object.\n\nNow that the worker is running, ``wait`` will return the result once the task\nis finished.\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":46,"id":736,"name":"__version__","nodeType":"Attribute","startLoc":46,"text":"__version__"},{"id":737,"name":"favicon.rst","nodeType":"TextFile","path":"docs/patterns","text":"Adding a favicon\n================\n\nA \"favicon\" is an icon used by browsers for tabs and bookmarks. This helps\nto distinguish your website and to give it a unique brand.\n\nA common question is how to add a favicon to a Flask application. First, of\ncourse, you need an icon. It should be 16 × 16 pixels and in the ICO file\nformat. This is not a requirement but a de-facto standard supported by all\nrelevant browsers. Put the icon in your static directory as\n:file:`favicon.ico`.\n\nNow, to get browsers to find your icon, the correct way is to add a link\ntag in your HTML. So, for example:\n\n.. sourcecode:: html+jinja\n\n \n\nThat's all you need for most browsers, however some really old ones do not\nsupport this standard. The old de-facto standard is to serve this file,\nwith this name, at the website root. If your application is not mounted at\nthe root path of the domain you either need to configure the web server to\nserve the icon at the root or if you can't do that you're out of luck. If\nhowever your application is the root you can simply route a redirect::\n\n app.add_url_rule('/favicon.ico',\n redirect_to=url_for('static', filename='favicon.ico'))\n\nIf you want to save the extra redirect request you can also write a view\nusing :func:`~flask.send_from_directory`::\n\n import os\n from flask import send_from_directory\n\n @app.route('/favicon.ico')\n def favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\nWe can leave out the explicit mimetype and it will be guessed, but we may\nas well specify it to avoid the extra guessing, as it will always be the\nsame.\n\nThe above will serve the icon via your application and if possible it's\nbetter to configure your dedicated web server to serve it; refer to the\nweb server's documentation.\n\nSee also\n--------\n\n* The `Favicon `_ article on\n Wikipedia\n"},{"id":738,"name":"templateinheritance.rst","nodeType":"TextFile","path":"docs/patterns","text":"Template Inheritance\n====================\n\nThe most powerful part of Jinja is template inheritance. Template inheritance\nallows you to build a base \"skeleton\" template that contains all the common\nelements of your site and defines **blocks** that child templates can override.\n\nSounds complicated but is very basic. It's easiest to understand it by starting\nwith an example.\n\n\nBase Template\n-------------\n\nThis template, which we'll call :file:`layout.html`, defines a simple HTML skeleton\ndocument that you might use for a simple two-column page. It's the job of\n\"child\" templates to fill the empty blocks with content:\n\n.. sourcecode:: html+jinja\n\n \n \n \n {% block head %}\n \n {% block title %}{% endblock %} - My Webpage\n {% endblock %}\n \n \n

{% block content %}{% endblock %}
\n
\n {% block footer %}\n © Copyright 2010 by you.\n {% endblock %}\n
\n \n \n\nIn this example, the ``{% block %}`` tags define four blocks that child templates\ncan fill in. All the `block` tag does is tell the template engine that a\nchild template may override those portions of the template.\n\nChild Template\n--------------\n\nA child template might look like this:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block title %}Index{% endblock %}\n {% block head %}\n {{ super() }}\n \n {% endblock %}\n {% block content %}\n

Index

\n

\n Welcome on my awesome homepage.\n {% endblock %}\n\nThe ``{% extends %}`` tag is the key here. It tells the template engine that\nthis template \"extends\" another template. When the template system evaluates\nthis template, first it locates the parent. The extends tag must be the\nfirst tag in the template. To render the contents of a block defined in\nthe parent template, use ``{{ super() }}``.\n"},{"id":739,"name":"static.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Static Files\n============\n\nThe authentication views and templates work, but they look very plain\nright now. Some `CSS`_ can be added to add style to the HTML layout you\nconstructed. The style won't change, so it's a *static* file rather than\na template.\n\nFlask automatically adds a ``static`` view that takes a path relative\nto the ``flaskr/static`` directory and serves it. The ``base.html``\ntemplate already has a link to the ``style.css`` file:\n\n.. code-block:: html+jinja\n\n {{ url_for('static', filename='style.css') }}\n\nBesides CSS, other types of static files might be files with JavaScript\nfunctions, or a logo image. They are all placed under the\n``flaskr/static`` directory and referenced with\n``url_for('static', filename='...')``.\n\nThis tutorial isn't focused on how to write CSS, so you can just copy\nthe following into the ``flaskr/static/style.css`` file:\n\n.. code-block:: css\n :caption: ``flaskr/static/style.css``\n\n html { font-family: sans-serif; background: #eee; padding: 1rem; }\n body { max-width: 960px; margin: 0 auto; background: white; }\n h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }\n a { color: #377ba8; }\n hr { border: none; border-top: 1px solid lightgray; }\n nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }\n nav h1 { flex: auto; margin: 0; }\n nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }\n nav ul { display: flex; list-style: none; margin: 0; padding: 0; }\n nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }\n .content { padding: 0 1rem 1rem; }\n .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }\n .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }\n .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }\n .post > header { display: flex; align-items: flex-end; font-size: 0.85em; }\n .post > header > div:first-of-type { flex: auto; }\n .post > header h1 { font-size: 1.5em; margin-bottom: 0; }\n .post .about { color: slategray; font-style: italic; }\n .post .body { white-space: pre-line; }\n .content:last-child { margin-bottom: 0; }\n .content form { margin: 1em 0; display: flex; flex-direction: column; }\n .content label { font-weight: bold; margin-bottom: 0.5em; }\n .content input, .content textarea { margin-bottom: 1em; }\n .content textarea { min-height: 12em; resize: vertical; }\n input.danger { color: #cc2f2e; }\n input[type=submit] { align-self: start; min-width: 10em; }\n\nYou can find a less compact version of ``style.css`` in the\n:gh:`example code `.\n\nGo to http://127.0.0.1:5000/auth/login and the page should look like the\nscreenshot below.\n\n.. image:: flaskr_login.png\n :align: center\n :class: screenshot\n :alt: screenshot of login page\n\nYou can read more about CSS from `Mozilla's documentation `_. If\nyou change a static file, refresh the browser page. If the change\ndoesn't show up, try clearing your browser's cache.\n\n.. _CSS: https://developer.mozilla.org/docs/Web/CSS\n\nContinue to :doc:`blog`.\n"},{"fileName":"setup.py","filePath":"examples/tutorial","id":740,"nodeType":"File","text":"from setuptools import setup\n\nsetup()\n"},{"col":0,"comment":"","endLoc":1,"header":"setup.py#","id":741,"name":"","nodeType":"Function","startLoc":1,"text":"setup()"},{"id":742,"name":"requestchecksum.rst","nodeType":"TextFile","path":"docs/patterns","text":"Request Content Checksums\n=========================\n\nVarious pieces of code can consume the request data and preprocess it.\nFor instance JSON data ends up on the request object already read and\nprocessed, form data ends up there as well but goes through a different\ncode path. This seems inconvenient when you want to calculate the\nchecksum of the incoming request data. This is necessary sometimes for\nsome APIs.\n\nFortunately this is however very simple to change by wrapping the input\nstream.\n\nThe following example calculates the SHA1 checksum of the incoming data as\nit gets read and stores it in the WSGI environment::\n\n import hashlib\n\n class ChecksumCalcStream(object):\n\n def __init__(self, stream):\n self._stream = stream\n self._hash = hashlib.sha1()\n\n def read(self, bytes):\n rv = self._stream.read(bytes)\n self._hash.update(rv)\n return rv\n\n def readline(self, size_hint):\n rv = self._stream.readline(size_hint)\n self._hash.update(rv)\n return rv\n\n def generate_checksum(request):\n env = request.environ\n stream = ChecksumCalcStream(env['wsgi.input'])\n env['wsgi.input'] = stream\n return stream._hash\n\nTo use this, all you need to do is to hook the calculating stream in\nbefore the request starts consuming data. (Eg: be careful accessing\n``request.form`` or anything of that nature. ``before_request_handlers``\nfor instance should be careful not to access it).\n\nExample usage::\n\n @app.route('/special-api', methods=['POST'])\n def special_api():\n hash = generate_checksum(request)\n # Accessing this parses the input stream\n files = request.files\n # At this point the hash is fully constructed.\n checksum = hash.hexdigest()\n return f\"Hash was: {checksum}\"\n"},{"id":743,"name":"LICENSE.rst","nodeType":"TextFile","path":"","text":"Copyright 2010 Pallets\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"id":744,"name":"LICENSE.rst","nodeType":"TextFile","path":"examples/javascript","text":"Copyright 2010 Pallets\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"fileName":"cli.py","filePath":"src/flask","id":745,"nodeType":"File","text":"import ast\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport warnings\nfrom functools import update_wrapper\nfrom operator import attrgetter\nfrom threading import Lock\nfrom threading import Thread\n\nimport click\nfrom werkzeug.utils import import_string\n\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_env\nfrom .helpers import get_load_dotenv\n\ntry:\n import dotenv\nexcept ImportError:\n dotenv = None\n\ntry:\n import ssl\nexcept ImportError:\n ssl = None # type: ignore\n\n\nclass NoAppException(click.UsageError):\n \"\"\"Raised if an application cannot be found or loaded.\"\"\"\n\n\ndef find_best_app(script_info, module):\n \"\"\"Given a module instance this tries to find the best possible\n application in the module or raises an exception.\n \"\"\"\n from . import Flask\n\n # Search for the most common names first.\n for attr_name in (\"app\", \"application\"):\n app = getattr(module, attr_name, None)\n\n if isinstance(app, Flask):\n return app\n\n # Otherwise find the only object that is a Flask instance.\n matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]\n\n if len(matches) == 1:\n return matches[0]\n elif len(matches) > 1:\n raise NoAppException(\n \"Detected multiple Flask applications in module\"\n f\" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'\"\n f\" to specify the correct one.\"\n )\n\n # Search for app factory functions.\n for attr_name in (\"create_app\", \"make_app\"):\n app_factory = getattr(module, attr_name, None)\n\n if inspect.isfunction(app_factory):\n try:\n app = call_factory(script_info, app_factory)\n\n if isinstance(app, Flask):\n return app\n except TypeError:\n if not _called_with_wrong_args(app_factory):\n raise\n raise NoAppException(\n f\"Detected factory {attr_name!r} in module {module.__name__!r},\"\n \" but could not call it without arguments. Use\"\n f\" \\\"FLASK_APP='{module.__name__}:{attr_name}(args)'\\\"\"\n \" to specify arguments.\"\n )\n\n raise NoAppException(\n \"Failed to find Flask application or factory in module\"\n f\" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'\"\n \" to specify one.\"\n )\n\n\ndef call_factory(script_info, app_factory, args=None, kwargs=None):\n \"\"\"Takes an app factory, a ``script_info` object and optionally a tuple\n of arguments. Checks for the existence of a script_info argument and calls\n the app_factory depending on that and the arguments provided.\n \"\"\"\n sig = inspect.signature(app_factory)\n args = [] if args is None else args\n kwargs = {} if kwargs is None else kwargs\n\n if \"script_info\" in sig.parameters:\n warnings.warn(\n \"The 'script_info' argument is deprecated and will not be\"\n \" passed to the app factory function in Flask 2.1.\",\n DeprecationWarning,\n )\n kwargs[\"script_info\"] = script_info\n\n if (\n not args\n and len(sig.parameters) == 1\n and next(iter(sig.parameters.values())).default is inspect.Parameter.empty\n ):\n warnings.warn(\n \"Script info is deprecated and will not be passed as the\"\n \" single argument to the app factory function in Flask\"\n \" 2.1.\",\n DeprecationWarning,\n )\n args.append(script_info)\n\n return app_factory(*args, **kwargs)\n\n\ndef _called_with_wrong_args(f):\n \"\"\"Check whether calling a function raised a ``TypeError`` because\n the call failed or because something in the factory raised the\n error.\n\n :param f: The function that was called.\n :return: ``True`` if the call failed.\n \"\"\"\n tb = sys.exc_info()[2]\n\n try:\n while tb is not None:\n if tb.tb_frame.f_code is f.__code__:\n # In the function, it was called successfully.\n return False\n\n tb = tb.tb_next\n\n # Didn't reach the function.\n return True\n finally:\n # Delete tb to break a circular reference.\n # https://docs.python.org/2/library/sys.html#sys.exc_info\n del tb\n\n\ndef find_app_by_string(script_info, module, app_name):\n \"\"\"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n \"\"\"\n from . import Flask\n\n # Parse app_name as a single expression to determine if it's a valid\n # attribute name or function call.\n try:\n expr = ast.parse(app_name.strip(), mode=\"eval\").body\n except SyntaxError:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n if isinstance(expr, ast.Name):\n name = expr.id\n args = kwargs = None\n elif isinstance(expr, ast.Call):\n # Ensure the function name is an attribute name only.\n if not isinstance(expr.func, ast.Name):\n raise NoAppException(\n f\"Function reference must be a simple name: {app_name!r}.\"\n )\n\n name = expr.func.id\n\n # Parse the positional and keyword arguments as literals.\n try:\n args = [ast.literal_eval(arg) for arg in expr.args]\n kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}\n except ValueError:\n # literal_eval gives cryptic error messages, show a generic\n # message with the full expression instead.\n raise NoAppException(\n f\"Failed to parse arguments as literal values: {app_name!r}.\"\n )\n else:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n try:\n attr = getattr(module, name)\n except AttributeError:\n raise NoAppException(\n f\"Failed to find attribute {name!r} in {module.__name__!r}.\"\n )\n\n # If the attribute is a function, call it with any args and kwargs\n # to get the real application.\n if inspect.isfunction(attr):\n try:\n app = call_factory(script_info, attr, args, kwargs)\n except TypeError:\n if not _called_with_wrong_args(attr):\n raise\n\n raise NoAppException(\n f\"The factory {app_name!r} in module\"\n f\" {module.__name__!r} could not be called with the\"\n \" specified arguments.\"\n )\n else:\n app = attr\n\n if isinstance(app, Flask):\n return app\n\n raise NoAppException(\n \"A valid Flask application was not obtained from\"\n f\" '{module.__name__}:{app_name}'.\"\n )\n\n\ndef prepare_import(path):\n \"\"\"Given a filename this will try to calculate the python path, add it\n to the search path and return the actual module name that is expected.\n \"\"\"\n path = os.path.realpath(path)\n\n fname, ext = os.path.splitext(path)\n if ext == \".py\":\n path = fname\n\n if os.path.basename(path) == \"__init__\":\n path = os.path.dirname(path)\n\n module_name = []\n\n # move up until outside package structure (no __init__.py)\n while True:\n path, name = os.path.split(path)\n module_name.append(name)\n\n if not os.path.exists(os.path.join(path, \"__init__.py\")):\n break\n\n if sys.path[0] != path:\n sys.path.insert(0, path)\n\n return \".\".join(module_name[::-1])\n\n\ndef locate_app(script_info, module_name, app_name, raise_if_not_found=True):\n __traceback_hide__ = True # noqa: F841\n\n try:\n __import__(module_name)\n except ImportError:\n # Reraise the ImportError if it occurred within the imported module.\n # Determine this by checking whether the trace has a depth > 1.\n if sys.exc_info()[2].tb_next:\n raise NoAppException(\n f\"While importing {module_name!r}, an ImportError was\"\n f\" raised:\\n\\n{traceback.format_exc()}\"\n )\n elif raise_if_not_found:\n raise NoAppException(f\"Could not import {module_name!r}.\")\n else:\n return\n\n module = sys.modules[module_name]\n\n if app_name is None:\n return find_best_app(script_info, module)\n else:\n return find_app_by_string(script_info, module, app_name)\n\n\ndef get_version(ctx, param, value):\n if not value or ctx.resilient_parsing:\n return\n\n import werkzeug\n from . import __version__\n\n click.echo(\n f\"Python {platform.python_version()}\\n\"\n f\"Flask {__version__}\\n\"\n f\"Werkzeug {werkzeug.__version__}\",\n color=ctx.color,\n )\n ctx.exit()\n\n\nversion_option = click.Option(\n [\"--version\"],\n help=\"Show the flask version\",\n expose_value=False,\n callback=get_version,\n is_flag=True,\n is_eager=True,\n)\n\n\nclass DispatchingApp:\n \"\"\"Special application that dispatches to a Flask application which\n is imported by name in a background thread. If an error happens\n it is recorded and shown as part of the WSGI handling which in case\n of the Werkzeug debugger means that it shows up in the browser.\n \"\"\"\n\n def __init__(self, loader, use_eager_loading=None):\n self.loader = loader\n self._app = None\n self._lock = Lock()\n self._bg_loading_exc_info = None\n\n if use_eager_loading is None:\n use_eager_loading = os.environ.get(\"WERKZEUG_RUN_MAIN\") != \"true\"\n\n if use_eager_loading:\n self._load_unlocked()\n else:\n self._load_in_background()\n\n def _load_in_background(self):\n def _load_app():\n __traceback_hide__ = True # noqa: F841\n with self._lock:\n try:\n self._load_unlocked()\n except Exception:\n self._bg_loading_exc_info = sys.exc_info()\n\n t = Thread(target=_load_app, args=())\n t.start()\n\n def _flush_bg_loading_exception(self):\n __traceback_hide__ = True # noqa: F841\n exc_info = self._bg_loading_exc_info\n if exc_info is not None:\n self._bg_loading_exc_info = None\n raise exc_info\n\n def _load_unlocked(self):\n __traceback_hide__ = True # noqa: F841\n self._app = rv = self.loader()\n self._bg_loading_exc_info = None\n return rv\n\n def __call__(self, environ, start_response):\n __traceback_hide__ = True # noqa: F841\n if self._app is not None:\n return self._app(environ, start_response)\n self._flush_bg_loading_exception()\n with self._lock:\n if self._app is not None:\n rv = self._app\n else:\n rv = self._load_unlocked()\n return rv(environ, start_response)\n\n\nclass ScriptInfo:\n \"\"\"Helper object to deal with Flask applications. This is usually not\n necessary to interface with as it's used internally in the dispatching\n to click. In future versions of Flask this object will most likely play\n a bigger role. Typically it's created automatically by the\n :class:`FlaskGroup` but you can also manually create it and pass it\n onwards as click object.\n \"\"\"\n\n def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path or os.environ.get(\"FLASK_APP\")\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data = {}\n self.set_debug_flag = set_debug_flag\n self._loaded_app = None\n\n def load_app(self):\n \"\"\"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n \"\"\"\n __traceback_hide__ = True # noqa: F841\n\n if self._loaded_app is not None:\n return self._loaded_app\n\n if self.create_app is not None:\n app = call_factory(self, self.create_app)\n else:\n if self.app_import_path:\n path, name = (\n re.split(r\":(?![\\\\/])\", self.app_import_path, 1) + [None]\n )[:2]\n import_name = prepare_import(path)\n app = locate_app(self, import_name, name)\n else:\n for path in (\"wsgi.py\", \"app.py\"):\n import_name = prepare_import(path)\n app = locate_app(self, import_name, None, raise_if_not_found=False)\n\n if app:\n break\n\n if not app:\n raise NoAppException(\n \"Could not locate a Flask application. You did not provide \"\n 'the \"FLASK_APP\" environment variable, and a \"wsgi.py\" or '\n '\"app.py\" module was not found in the current directory.'\n )\n\n if self.set_debug_flag:\n # Update the app's debug flag through the descriptor so that\n # other values repopulate as well.\n app.debug = get_debug_flag()\n\n self._loaded_app = app\n return app\n\n\npass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)\n\n\ndef with_appcontext(f):\n \"\"\"Wraps a callback so that it's guaranteed to be executed with the\n script's application context. If callbacks are registered directly\n to the ``app.cli`` object then they are wrapped with this function\n by default unless it's disabled.\n \"\"\"\n\n @click.pass_context\n def decorator(__ctx, *args, **kwargs):\n with __ctx.ensure_object(ScriptInfo).load_app().app_context():\n return __ctx.invoke(f, *args, **kwargs)\n\n return update_wrapper(decorator, f)\n\n\nclass AppGroup(click.Group):\n \"\"\"This works similar to a regular click :class:`~click.Group` but it\n changes the behavior of the :meth:`command` decorator so that it\n automatically wraps the functions in :func:`with_appcontext`.\n\n Not to be confused with :class:`FlaskGroup`.\n \"\"\"\n\n def command(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f):\n if wrap_for_ctx:\n f = with_appcontext(f)\n return click.Group.command(self, *args, **kwargs)(f)\n\n return decorator\n\n def group(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n \"\"\"\n kwargs.setdefault(\"cls\", AppGroup)\n return click.Group.group(self, *args, **kwargs)\n\n\nclass FlaskGroup(AppGroup):\n \"\"\"Special subclass of the :class:`AppGroup` group that supports\n loading more commands from the configured Flask app. Normally a\n developer does not have to interface with this class but there are\n some very advanced use cases for which it makes sense to create an\n instance of this. see :ref:`custom-scripts`.\n\n :param add_default_commands: if this is True then the default run and\n shell commands will be added.\n :param add_version_option: adds the ``--version`` option.\n :param create_app: an optional callback that is passed the script info and\n returns the loaded app.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param set_debug_flag: Set the app's debug flag based on the active\n environment\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment variables\n from :file:`.env` and :file:`.flaskenv` files.\n \"\"\"\n\n def __init__(\n self,\n add_default_commands=True,\n create_app=None,\n add_version_option=True,\n load_dotenv=True,\n set_debug_flag=True,\n **extra,\n ):\n params = list(extra.pop(\"params\", None) or ())\n\n if add_version_option:\n params.append(version_option)\n\n AppGroup.__init__(self, params=params, **extra)\n self.create_app = create_app\n self.load_dotenv = load_dotenv\n self.set_debug_flag = set_debug_flag\n\n if add_default_commands:\n self.add_command(run_command)\n self.add_command(shell_command)\n self.add_command(routes_command)\n\n self._loaded_plugin_commands = False\n\n def _load_plugin_commands(self):\n if self._loaded_plugin_commands:\n return\n try:\n import pkg_resources\n except ImportError:\n self._loaded_plugin_commands = True\n return\n\n for ep in pkg_resources.iter_entry_points(\"flask.commands\"):\n self.add_command(ep.load(), ep.name)\n self._loaded_plugin_commands = True\n\n def get_command(self, ctx, name):\n self._load_plugin_commands()\n # Look up built-in and plugin commands, which should be\n # available even if the app fails to load.\n rv = super().get_command(ctx, name)\n\n if rv is not None:\n return rv\n\n info = ctx.ensure_object(ScriptInfo)\n\n # Look up commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n return info.load_app().cli.get_command(ctx, name)\n except NoAppException as e:\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n\n def list_commands(self, ctx):\n self._load_plugin_commands()\n # Start with the built-in and plugin commands.\n rv = set(super().list_commands(ctx))\n info = ctx.ensure_object(ScriptInfo)\n\n # Add commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n rv.update(info.load_app().cli.list_commands(ctx))\n except NoAppException as e:\n # When an app couldn't be loaded, show the error message\n # without the traceback.\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n except Exception:\n # When any other errors occurred during loading, show the\n # full traceback.\n click.secho(f\"{traceback.format_exc()}\\n\", err=True, fg=\"red\")\n\n return sorted(rv)\n\n def main(self, *args, **kwargs):\n # Set a global flag that indicates that we were invoked from the\n # command line interface. This is detected by Flask.run to make the\n # call into a no-op. This is necessary to avoid ugly errors when the\n # script that is loaded here also attempts to start a server.\n os.environ[\"FLASK_RUN_FROM_CLI\"] = \"true\"\n\n if get_load_dotenv(self.load_dotenv):\n load_dotenv()\n\n obj = kwargs.get(\"obj\")\n\n if obj is None:\n obj = ScriptInfo(\n create_app=self.create_app, set_debug_flag=self.set_debug_flag\n )\n\n kwargs[\"obj\"] = obj\n kwargs.setdefault(\"auto_envvar_prefix\", \"FLASK\")\n return super().main(*args, **kwargs)\n\n\ndef _path_is_ancestor(path, other):\n \"\"\"Take ``other`` and remove the length of ``path`` from it. Then join it\n to ``path``. If it is the original value, ``path`` is an ancestor of\n ``other``.\"\"\"\n return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other\n\n\ndef load_dotenv(path=None):\n \"\"\"Load \"dotenv\" files in order of precedence to set environment variables.\n\n If an env var is already set it is not overwritten, so earlier files in the\n list are preferred over later files.\n\n This is a no-op if `python-dotenv`_ is not installed.\n\n .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n\n :param path: Load the file at this location instead of searching.\n :return: ``True`` if a file was loaded.\n\n .. versionchanged:: 1.1.0\n Returns ``False`` when python-dotenv is not installed, or when\n the given path isn't a file.\n\n .. versionchanged:: 2.0\n When loading the env files, set the default encoding to UTF-8.\n\n .. versionadded:: 1.0\n \"\"\"\n if dotenv is None:\n if path or os.path.isfile(\".env\") or os.path.isfile(\".flaskenv\"):\n click.secho(\n \" * Tip: There are .env or .flaskenv files present.\"\n ' Do \"pip install python-dotenv\" to use them.',\n fg=\"yellow\",\n err=True,\n )\n\n return False\n\n # if the given path specifies the actual file then return True,\n # else False\n if path is not None:\n if os.path.isfile(path):\n return dotenv.load_dotenv(path, encoding=\"utf-8\")\n\n return False\n\n new_dir = None\n\n for name in (\".env\", \".flaskenv\"):\n path = dotenv.find_dotenv(name, usecwd=True)\n\n if not path:\n continue\n\n if new_dir is None:\n new_dir = os.path.dirname(path)\n\n dotenv.load_dotenv(path, encoding=\"utf-8\")\n\n return new_dir is not None # at least one file was located and loaded\n\n\ndef show_server_banner(env, debug, app_import_path, eager_loading):\n \"\"\"Show extra startup messages the first time the server is run,\n ignoring the reloader.\n \"\"\"\n if os.environ.get(\"WERKZEUG_RUN_MAIN\") == \"true\":\n return\n\n if app_import_path is not None:\n message = f\" * Serving Flask app {app_import_path!r}\"\n\n if not eager_loading:\n message += \" (lazy loading)\"\n\n click.echo(message)\n\n click.echo(f\" * Environment: {env}\")\n\n if env == \"production\":\n click.secho(\n \" WARNING: This is a development server. Do not use it in\"\n \" a production deployment.\",\n fg=\"red\",\n )\n click.secho(\" Use a production WSGI server instead.\", dim=True)\n\n if debug is not None:\n click.echo(f\" * Debug mode: {'on' if debug else 'off'}\")\n\n\nclass CertParamType(click.ParamType):\n \"\"\"Click option type for the ``--cert`` option. Allows either an\n existing file, the string ``'adhoc'``, or an import for a\n :class:`~ssl.SSLContext` object.\n \"\"\"\n\n name = \"path\"\n\n def __init__(self):\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n def convert(self, value, param, ctx):\n if ssl is None:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n )\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower()\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptography library.\",\n ctx,\n param,\n )\n\n return value\n\n obj = import_string(value, silent=True)\n\n if isinstance(obj, ssl.SSLContext):\n return obj\n\n raise\n\n\ndef _validate_key(ctx, param, value):\n \"\"\"The ``--key`` option must be specified when ``--cert`` is a file.\n Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.\n \"\"\"\n cert = ctx.params.get(\"cert\")\n is_adhoc = cert == \"adhoc\"\n is_context = ssl and isinstance(cert, ssl.SSLContext)\n\n if value is not None:\n if is_adhoc:\n raise click.BadParameter(\n 'When \"--cert\" is \"adhoc\", \"--key\" is not used.', ctx, param\n )\n\n if is_context:\n raise click.BadParameter(\n 'When \"--cert\" is an SSLContext object, \"--key is not used.', ctx, param\n )\n\n if not cert:\n raise click.BadParameter('\"--cert\" must also be specified.', ctx, param)\n\n ctx.params[\"cert\"] = cert, value\n\n else:\n if cert and not (is_adhoc or is_context):\n raise click.BadParameter('Required when using \"--cert\".', ctx, param)\n\n return value\n\n\nclass SeparatedPathType(click.Path):\n \"\"\"Click option type that accepts a list of values separated by the\n OS's path separator (``:``, ``;`` on Windows). Each value is\n validated as a :class:`click.Path` type.\n \"\"\"\n\n def convert(self, value, param, ctx):\n items = self.split_envvar_value(value)\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]\n\n\n@click.command(\"run\", short_help=\"Run a development server.\")\n@click.option(\"--host\", \"-h\", default=\"127.0.0.1\", help=\"The interface to bind to.\")\n@click.option(\"--port\", \"-p\", default=5000, help=\"The port to bind to.\")\n@click.option(\n \"--cert\", type=CertParamType(), help=\"Specify a certificate file to use HTTPS.\"\n)\n@click.option(\n \"--key\",\n type=click.Path(exists=True, dir_okay=False, resolve_path=True),\n callback=_validate_key,\n expose_value=False,\n help=\"The key file to use when specifying a certificate.\",\n)\n@click.option(\n \"--reload/--no-reload\",\n default=None,\n help=\"Enable or disable the reloader. By default the reloader \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--debugger/--no-debugger\",\n default=None,\n help=\"Enable or disable the debugger. By default the debugger \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--eager-loading/--lazy-loading\",\n default=None,\n help=\"Enable or disable eager loading. By default eager \"\n \"loading is enabled if the reloader is disabled.\",\n)\n@click.option(\n \"--with-threads/--without-threads\",\n default=True,\n help=\"Enable or disable multithreading.\",\n)\n@click.option(\n \"--extra-files\",\n default=None,\n type=SeparatedPathType(),\n help=(\n \"Extra files that trigger a reload on change. Multiple paths\"\n f\" are separated by {os.path.pathsep!r}.\"\n ),\n)\n@pass_script_info\ndef run_command(\n info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files\n):\n \"\"\"Run a local development server.\n\n This server is for development purposes only. It does not provide\n the stability, security, or performance of production WSGI servers.\n\n The reloader and debugger are enabled by default if\n FLASK_ENV=development or FLASK_DEBUG=1.\n \"\"\"\n debug = get_debug_flag()\n\n if reload is None:\n reload = debug\n\n if debugger is None:\n debugger = debug\n\n show_server_banner(get_env(), debug, info.app_import_path, eager_loading)\n app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)\n\n from werkzeug.serving import run_simple\n\n run_simple(\n host,\n port,\n app,\n use_reloader=reload,\n use_debugger=debugger,\n threaded=with_threads,\n ssl_context=cert,\n extra_files=extra_files,\n )\n\n\n@click.command(\"shell\", short_help=\"Run a shell in the app context.\")\n@with_appcontext\ndef shell_command() -> None:\n \"\"\"Run an interactive Python shell in the context of a given\n Flask application. The application will populate the default\n namespace of this shell according to its configuration.\n\n This is useful for executing small snippets of management code\n without having to manually configure the application.\n \"\"\"\n import code\n from .globals import _app_ctx_stack\n\n app = _app_ctx_stack.top.app\n banner = (\n f\"Python {sys.version} on {sys.platform}\\n\"\n f\"App: {app.import_name} [{app.env}]\\n\"\n f\"Instance: {app.instance_path}\"\n )\n ctx: dict = {}\n\n # Support the regular Python interpreter startup script if someone\n # is using it.\n startup = os.environ.get(\"PYTHONSTARTUP\")\n if startup and os.path.isfile(startup):\n with open(startup) as f:\n eval(compile(f.read(), startup, \"exec\"), ctx)\n\n ctx.update(app.make_shell_context())\n\n # Site, customize, or startup script can set a hook to call when\n # entering interactive mode. The default one sets up readline with\n # tab and history completion.\n interactive_hook = getattr(sys, \"__interactivehook__\", None)\n\n if interactive_hook is not None:\n try:\n import readline\n from rlcompleter import Completer\n except ImportError:\n pass\n else:\n # rlcompleter uses __main__.__dict__ by default, which is\n # flask.__main__. Use the shell context instead.\n readline.set_completer(Completer(ctx).complete)\n\n interactive_hook()\n\n code.interact(banner=banner, local=ctx)\n\n\n@click.command(\"routes\", short_help=\"Show the routes for the app.\")\n@click.option(\n \"--sort\",\n \"-s\",\n type=click.Choice((\"endpoint\", \"methods\", \"rule\", \"match\")),\n default=\"endpoint\",\n help=(\n 'Method to sort routes by. \"match\" is the order that Flask will match '\n \"routes when dispatching a request.\"\n ),\n)\n@click.option(\"--all-methods\", is_flag=True, help=\"Show HEAD and OPTIONS methods.\")\n@with_appcontext\ndef routes_command(sort: str, all_methods: bool) -> None:\n \"\"\"Show all registered routes with endpoints and methods.\"\"\"\n\n rules = list(current_app.url_map.iter_rules())\n if not rules:\n click.echo(\"No routes were registered.\")\n return\n\n ignored_methods = set(() if all_methods else (\"HEAD\", \"OPTIONS\"))\n\n if sort in (\"endpoint\", \"rule\"):\n rules = sorted(rules, key=attrgetter(sort))\n elif sort == \"methods\":\n rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore\n\n rule_methods = [\n \", \".join(sorted(rule.methods - ignored_methods)) # type: ignore\n for rule in rules\n ]\n\n headers = (\"Endpoint\", \"Methods\", \"Rule\")\n widths = (\n max(len(rule.endpoint) for rule in rules),\n max(len(methods) for methods in rule_methods),\n max(len(rule.rule) for rule in rules),\n )\n widths = [max(len(h), w) for h, w in zip(headers, widths)]\n row = \"{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}\".format(*widths)\n\n click.echo(row.format(*headers).strip())\n click.echo(row.format(*(\"-\" * width for width in widths)))\n\n for rule, methods in zip(rules, rule_methods):\n click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())\n\n\ncli = FlaskGroup(\n help=\"\"\"\\\nA general utility script for Flask applications.\n\nProvides commands from Flask, extensions, and the application. Loads the\napplication defined in the FLASK_APP environment variable, or from a wsgi.py\nfile. Setting the FLASK_ENV environment variable to 'development' will enable\ndebug mode.\n\n\\b\n {prefix}{cmd} FLASK_APP=hello.py\n {prefix}{cmd} FLASK_ENV=development\n {prefix}flask run\n\"\"\".format(\n cmd=\"export\" if os.name == \"posix\" else \"set\",\n prefix=\"$ \" if os.name == \"posix\" else \"> \",\n )\n)\n\n\ndef main() -> None:\n if int(click.__version__[0]) < 8:\n warnings.warn(\n \"Using the `flask` cli with Click 7 is deprecated and\"\n \" will not be supported starting with Flask 2.1.\"\n \" Please upgrade to Click 8 as soon as possible.\",\n DeprecationWarning,\n )\n # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed\n cli.main(args=sys.argv[1:])\n\n\nif __name__ == \"__main__\":\n main()\n"},{"attributeType":"null","col":8,"comment":"null","endLoc":230,"id":746,"name":"url_adapter","nodeType":"Attribute","startLoc":230,"text":"self.url_adapter"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":747,"name":"","nodeType":"Function","startLoc":1,"text":"__version__ = \"2.0.1.dev0\""},{"className":"RequestContext","col":0,"comment":"The request context contains all request relevant information. It is\n created at the beginning of the request and pushed to the\n `_request_ctx_stack` and removed at the end of it. It will create the\n URL adapter and request object for the WSGI environment provided.\n\n Do not attempt to use this class directly, instead use\n :meth:`~flask.Flask.test_request_context` and\n :meth:`~flask.Flask.request_context` to create this object.\n\n When the request context is popped, it will evaluate all the\n functions registered on the application for teardown execution\n (:meth:`~flask.Flask.teardown_request`).\n\n The request context is automatically popped at the end of the request\n for you. In debug mode the request context is kept around if\n exceptions happen so that interactive debuggers have a chance to\n introspect the data. With 0.4 this can also be forced for requests\n that did not fail and outside of ``DEBUG`` mode. By setting\n ``'flask._preserve_context'`` to ``True`` on the WSGI environment the\n context will not pop itself at the end of the request. This is used by\n the :meth:`~flask.Flask.test_client` for example to implement the\n deferred cleanup functionality.\n\n You might find this helpful for unittests where you need the\n information from the context local around for a little longer. Make\n sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in\n that situation, otherwise your unittests will leak memory.\n ","endLoc":478,"id":748,"nodeType":"Class","startLoc":266,"text":"class RequestContext:\n \"\"\"The request context contains all request relevant information. It is\n created at the beginning of the request and pushed to the\n `_request_ctx_stack` and removed at the end of it. It will create the\n URL adapter and request object for the WSGI environment provided.\n\n Do not attempt to use this class directly, instead use\n :meth:`~flask.Flask.test_request_context` and\n :meth:`~flask.Flask.request_context` to create this object.\n\n When the request context is popped, it will evaluate all the\n functions registered on the application for teardown execution\n (:meth:`~flask.Flask.teardown_request`).\n\n The request context is automatically popped at the end of the request\n for you. In debug mode the request context is kept around if\n exceptions happen so that interactive debuggers have a chance to\n introspect the data. With 0.4 this can also be forced for requests\n that did not fail and outside of ``DEBUG`` mode. By setting\n ``'flask._preserve_context'`` to ``True`` on the WSGI environment the\n context will not pop itself at the end of the request. This is used by\n the :meth:`~flask.Flask.test_client` for example to implement the\n deferred cleanup functionality.\n\n You might find this helpful for unittests where you need the\n information from the context local around for a little longer. Make\n sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in\n that situation, otherwise your unittests will leak memory.\n \"\"\"\n\n def __init__(\n self,\n app: \"Flask\",\n environ: dict,\n request: t.Optional[\"Request\"] = None,\n session: t.Optional[\"SessionMixin\"] = None,\n ) -> None:\n self.app = app\n if request is None:\n request = app.request_class(environ)\n self.request = request\n self.url_adapter = None\n try:\n self.url_adapter = app.create_url_adapter(self.request)\n except HTTPException as e:\n self.request.routing_exception = e\n self.flashes = None\n self.session = session\n\n # Request contexts can be pushed multiple times and interleaved with\n # other request contexts. Now only if the last level is popped we\n # get rid of them. Additionally if an application context is missing\n # one is created implicitly so for each level we add this information\n self._implicit_app_ctx_stack: t.List[t.Optional[\"AppContext\"]] = []\n\n # indicator if the context was preserved. Next time another context\n # is pushed the preserved context is popped.\n self.preserved = False\n\n # remembers the exception for pop if there is one in case the context\n # preservation kicks in.\n self._preserved_exc = None\n\n # Functions that should be executed after the request on the response\n # object. These will be called before the regular \"after_request\"\n # functions.\n self._after_request_functions: t.List[AfterRequestCallable] = []\n\n @property\n def g(self) -> AppContext:\n return _app_ctx_stack.top.g\n\n @g.setter\n def g(self, value: AppContext) -> None:\n _app_ctx_stack.top.g = value\n\n def copy(self) -> \"RequestContext\":\n \"\"\"Creates a copy of this request context with the same request object.\n This can be used to move a request context to a different greenlet.\n Because the actual request object is the same this cannot be used to\n move a request context to a different thread unless access to the\n request object is locked.\n\n .. versionadded:: 0.10\n\n .. versionchanged:: 1.1\n The current session object is used instead of reloading the original\n data. This prevents `flask.session` pointing to an out-of-date object.\n \"\"\"\n return self.__class__(\n self.app,\n environ=self.request.environ,\n request=self.request,\n session=self.session,\n )\n\n def match_request(self) -> None:\n \"\"\"Can be overridden by a subclass to hook into the matching\n of the request.\n \"\"\"\n try:\n result = self.url_adapter.match(return_rule=True) # type: ignore\n self.request.url_rule, self.request.view_args = result # type: ignore\n except HTTPException as e:\n self.request.routing_exception = e\n\n def push(self) -> None:\n \"\"\"Binds the request context to the current context.\"\"\"\n # If an exception occurs in debug mode or if context preservation is\n # activated under exception situations exactly one context stays\n # on the stack. The rationale is that you want to access that\n # information under debug situations. However if someone forgets to\n # pop that context again we want to make sure that on the next push\n # it's invalidated, otherwise we run at risk that something leaks\n # memory. This is usually only a problem in test suite since this\n # functionality is not active in production environments.\n top = _request_ctx_stack.top\n if top is not None and top.preserved:\n top.pop(top._preserved_exc)\n\n # Before we push the request context we have to ensure that there\n # is an application context.\n app_ctx = _app_ctx_stack.top\n if app_ctx is None or app_ctx.app != self.app:\n app_ctx = self.app.app_context()\n app_ctx.push()\n self._implicit_app_ctx_stack.append(app_ctx)\n else:\n self._implicit_app_ctx_stack.append(None)\n\n _request_ctx_stack.push(self)\n\n if self.url_adapter is not None:\n self.match_request()\n\n # Open the session at the moment that the request context is available.\n # This allows a custom open_session method to use the request context.\n # Only open a new session if this is the first time the request was\n # pushed, otherwise stream_with_context loses the session.\n if self.session is None:\n session_interface = self.app.session_interface\n self.session = session_interface.open_session(self.app, self.request)\n\n if self.session is None:\n self.session = session_interface.make_null_session(self.app)\n\n def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore\n \"\"\"Pops the request context and unbinds it by doing that. This will\n also trigger the execution of functions registered by the\n :meth:`~flask.Flask.teardown_request` decorator.\n\n .. versionchanged:: 0.9\n Added the `exc` argument.\n \"\"\"\n app_ctx = self._implicit_app_ctx_stack.pop()\n clear_request = False\n\n try:\n if not self._implicit_app_ctx_stack:\n self.preserved = False\n self._preserved_exc = None\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n self.app.do_teardown_request(exc)\n\n request_close = getattr(self.request, \"close\", None)\n if request_close is not None:\n request_close()\n clear_request = True\n finally:\n rv = _request_ctx_stack.pop()\n\n # get rid of circular dependencies at the end of the request\n # so that we don't require the GC to be active.\n if clear_request:\n rv.request.environ[\"werkzeug.request\"] = None\n\n # Get rid of the app as well if necessary.\n if app_ctx is not None:\n app_ctx.pop(exc)\n\n assert (\n rv is self\n ), f\"Popped wrong request context. ({rv!r} instead of {self!r})\"\n\n def auto_pop(self, exc: t.Optional[BaseException]) -> None:\n if self.request.environ.get(\"flask._preserve_context\") or (\n exc is not None and self.app.preserve_context_on_exception\n ):\n self.preserved = True\n self._preserved_exc = exc # type: ignore\n else:\n self.pop(exc)\n\n def __enter__(self) -> \"RequestContext\":\n self.push()\n return self\n\n def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n # do not pop the request stack if we are in debug mode and an\n # exception happened. This will allow the debugger to still\n # access the request object in the interactive shell. Furthermore\n # the context can be force kept alive for the test client.\n # See flask.testing for how this works.\n self.auto_pop(exc_value)\n\n def __repr__(self) -> str:\n return (\n f\"<{type(self).__name__} {self.request.url!r}\"\n f\" [{self.request.method}] of {self.app.name}>\"\n )"},{"className":"NoAppException","col":0,"comment":"Raised if an application cannot be found or loaded.","endLoc":34,"id":749,"nodeType":"Class","startLoc":33,"text":"class NoAppException(click.UsageError):\n \"\"\"Raised if an application cannot be found or loaded.\"\"\""},{"col":4,"comment":"null","endLoc":336,"header":"@property\n def g(self) -> AppContext","id":750,"name":"g","nodeType":"Function","startLoc":334,"text":"@property\n def g(self) -> AppContext:\n return _app_ctx_stack.top.g"},{"col":4,"comment":"null","endLoc":340,"header":"@g.setter\n def g(self, value: AppContext) -> None","id":751,"name":"g","nodeType":"Function","startLoc":338,"text":"@g.setter\n def g(self, value: AppContext) -> None:\n _app_ctx_stack.top.g = value"},{"col":4,"comment":"Creates a copy of this request context with the same request object.\n This can be used to move a request context to a different greenlet.\n Because the actual request object is the same this cannot be used to\n move a request context to a different thread unless access to the\n request object is locked.\n\n .. versionadded:: 0.10\n\n .. versionchanged:: 1.1\n The current session object is used instead of reloading the original\n data. This prevents `flask.session` pointing to an out-of-date object.\n ","endLoc":360,"header":"def copy(self) -> \"RequestContext\"","id":752,"name":"copy","nodeType":"Function","startLoc":342,"text":"def copy(self) -> \"RequestContext\":\n \"\"\"Creates a copy of this request context with the same request object.\n This can be used to move a request context to a different greenlet.\n Because the actual request object is the same this cannot be used to\n move a request context to a different thread unless access to the\n request object is locked.\n\n .. versionadded:: 0.10\n\n .. versionchanged:: 1.1\n The current session object is used instead of reloading the original\n data. This prevents `flask.session` pointing to an out-of-date object.\n \"\"\"\n return self.__class__(\n self.app,\n environ=self.request.environ,\n request=self.request,\n session=self.session,\n )"},{"className":"DispatchingApp","col":0,"comment":"Special application that dispatches to a Flask application which\n is imported by name in a background thread. If an error happens\n it is recorded and shown as part of the WSGI handling which in case\n of the Werkzeug debugger means that it shows up in the browser.\n ","endLoc":360,"id":753,"nodeType":"Class","startLoc":304,"text":"class DispatchingApp:\n \"\"\"Special application that dispatches to a Flask application which\n is imported by name in a background thread. If an error happens\n it is recorded and shown as part of the WSGI handling which in case\n of the Werkzeug debugger means that it shows up in the browser.\n \"\"\"\n\n def __init__(self, loader, use_eager_loading=None):\n self.loader = loader\n self._app = None\n self._lock = Lock()\n self._bg_loading_exc_info = None\n\n if use_eager_loading is None:\n use_eager_loading = os.environ.get(\"WERKZEUG_RUN_MAIN\") != \"true\"\n\n if use_eager_loading:\n self._load_unlocked()\n else:\n self._load_in_background()\n\n def _load_in_background(self):\n def _load_app():\n __traceback_hide__ = True # noqa: F841\n with self._lock:\n try:\n self._load_unlocked()\n except Exception:\n self._bg_loading_exc_info = sys.exc_info()\n\n t = Thread(target=_load_app, args=())\n t.start()\n\n def _flush_bg_loading_exception(self):\n __traceback_hide__ = True # noqa: F841\n exc_info = self._bg_loading_exc_info\n if exc_info is not None:\n self._bg_loading_exc_info = None\n raise exc_info\n\n def _load_unlocked(self):\n __traceback_hide__ = True # noqa: F841\n self._app = rv = self.loader()\n self._bg_loading_exc_info = None\n return rv\n\n def __call__(self, environ, start_response):\n __traceback_hide__ = True # noqa: F841\n if self._app is not None:\n return self._app(environ, start_response)\n self._flush_bg_loading_exception()\n with self._lock:\n if self._app is not None:\n rv = self._app\n else:\n rv = self._load_unlocked()\n return rv(environ, start_response)"},{"col":4,"comment":"null","endLoc":323,"header":"def __init__(self, loader, use_eager_loading=None)","id":754,"name":"__init__","nodeType":"Function","startLoc":311,"text":"def __init__(self, loader, use_eager_loading=None):\n self.loader = loader\n self._app = None\n self._lock = Lock()\n self._bg_loading_exc_info = None\n\n if use_eager_loading is None:\n use_eager_loading = os.environ.get(\"WERKZEUG_RUN_MAIN\") != \"true\"\n\n if use_eager_loading:\n self._load_unlocked()\n else:\n self._load_in_background()"},{"id":755,"name":"Makefile","nodeType":"TextFile","path":"docs","text":"# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the environment for the first two.\nSPHINXOPTS ?=\nSPHINXBUILD ?= sphinx-build\nSOURCEDIR = .\nBUILDDIR = _build\n\n# Put it first so that \"make\" without argument is like \"make help\".\nhelp:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n.PHONY: help Makefile\n\n# Catch-all target: route all unknown targets to Sphinx using the new\n# \"make mode\" option. $(O) is meant as a shortcut for $(SPHINXOPTS).\n%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n"},{"id":756,"name":"config.json","nodeType":"TextFile","path":"tests/static","text":"{\n \"TEST_KEY\": \"foo\",\n \"SECRET_KEY\": \"config\"\n}\n"},{"id":757,"name":"simple_template.html","nodeType":"TextFile","path":"tests/templates","text":"

{{ whiskey }}

\n"},{"id":758,"name":"non_escaping_template.txt","nodeType":"TextFile","path":"tests/templates","text":"{{ text }}\n{{ html }}\n{% autoescape false %}{{ text }}\n{{ html }}{% endautoescape %}\n{% autoescape true %}{{ text }}\n{{ html }}{% endautoescape %}\n{{ text }}\n{{ html }}\n"},{"id":759,"name":"tests","nodeType":"Package"},{"fileName":"conftest.py","filePath":"tests","id":760,"nodeType":"File","text":"import os\nimport pkgutil\nimport sys\nimport textwrap\n\nimport pytest\nfrom _pytest import monkeypatch\n\nimport flask\nfrom flask import Flask as _Flask\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ():\n \"\"\"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n \"\"\"\n mp = monkeypatch.MonkeyPatch()\n out = (\n (os.environ, \"FLASK_APP\", monkeypatch.notset),\n (os.environ, \"FLASK_ENV\", monkeypatch.notset),\n (os.environ, \"FLASK_DEBUG\", monkeypatch.notset),\n (os.environ, \"FLASK_RUN_FROM_CLI\", monkeypatch.notset),\n (os.environ, \"WERKZEUG_RUN_MAIN\", monkeypatch.notset),\n )\n\n for _, key, value in out:\n if value is monkeypatch.notset:\n mp.delenv(key, False)\n else:\n mp.setenv(key, value)\n\n yield out\n mp.undo()\n\n\n@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ):\n \"\"\"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n \"\"\"\n monkeypatch._setitem.extend(_standard_os_environ)\n\n\nclass Flask(_Flask):\n testing = True\n secret_key = \"test key\"\n\n\n@pytest.fixture\ndef app():\n app = Flask(\"flask_test\", root_path=os.path.dirname(__file__))\n return app\n\n\n@pytest.fixture\ndef app_ctx(app):\n with app.app_context() as ctx:\n yield ctx\n\n\n@pytest.fixture\ndef req_ctx(app):\n with app.test_request_context() as ctx:\n yield ctx\n\n\n@pytest.fixture\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture\ndef test_apps(monkeypatch):\n monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), \"test_apps\"))\n original_modules = set(sys.modules.keys())\n\n yield\n\n # Remove any imports cached during the test. Otherwise \"import app\"\n # will work in the next test even though it's no longer on the path.\n for key in sys.modules.keys() - original_modules:\n sys.modules.pop(key)\n\n\n@pytest.fixture(autouse=True)\ndef leak_detector():\n yield\n\n # make sure we're not leaking a request context since we are\n # testing flask internally in debug mode in a few cases\n leaks = []\n while flask._request_ctx_stack.top is not None:\n leaks.append(flask._request_ctx_stack.pop())\n assert leaks == []\n\n\n@pytest.fixture(params=(True, False))\ndef limit_loader(request, monkeypatch):\n \"\"\"Patch pkgutil.get_loader to give loader without get_filename or archive.\n\n This provides for tests where a system has custom loaders, e.g. Google App\n Engine's HardenedModulesHook, which have neither the `get_filename` method\n nor the `archive` attribute.\n\n This fixture will run the testcase twice, once with and once without the\n limitation/mock.\n \"\"\"\n if not request.param:\n return\n\n class LimitedLoader:\n def __init__(self, loader):\n self.loader = loader\n\n def __getattr__(self, name):\n if name in {\"archive\", \"get_filename\"}:\n raise AttributeError(f\"Mocking a loader which does not have {name!r}.\")\n return getattr(self.loader, name)\n\n old_get_loader = pkgutil.get_loader\n\n def get_loader(*args, **kwargs):\n return LimitedLoader(old_get_loader(*args, **kwargs))\n\n monkeypatch.setattr(pkgutil, \"get_loader\", get_loader)\n\n\n@pytest.fixture\ndef modules_tmpdir(tmpdir, monkeypatch):\n \"\"\"A tmpdir added to sys.path.\"\"\"\n rv = tmpdir.mkdir(\"modules_tmpdir\")\n monkeypatch.syspath_prepend(str(rv))\n return rv\n\n\n@pytest.fixture\ndef modules_tmpdir_prefix(modules_tmpdir, monkeypatch):\n monkeypatch.setattr(sys, \"prefix\", str(modules_tmpdir))\n return modules_tmpdir\n\n\n@pytest.fixture\ndef site_packages(modules_tmpdir, monkeypatch):\n \"\"\"Create a fake site-packages.\"\"\"\n rv = (\n modules_tmpdir.mkdir(\"lib\")\n .mkdir(f\"python{sys.version_info.major}.{sys.version_info.minor}\")\n .mkdir(\"site-packages\")\n )\n monkeypatch.syspath_prepend(str(rv))\n return rv\n\n\n@pytest.fixture\ndef install_egg(modules_tmpdir, monkeypatch):\n \"\"\"Generate egg from package name inside base and put the egg into\n sys.path.\"\"\"\n\n def inner(name, base=modules_tmpdir):\n base.join(name).ensure_dir()\n base.join(name).join(\"__init__.py\").ensure()\n\n egg_setup = base.join(\"setup.py\")\n egg_setup.write(\n textwrap.dedent(\n f\"\"\"\n from setuptools import setup\n setup(\n name=\"{name}\",\n version=\"1.0\",\n packages=[\"site_egg\"],\n zip_safe=True,\n )\n \"\"\"\n )\n )\n\n import subprocess\n\n subprocess.check_call(\n [sys.executable, \"setup.py\", \"bdist_egg\"], cwd=str(modules_tmpdir)\n )\n (egg_path,) = modules_tmpdir.join(\"dist/\").listdir()\n monkeypatch.syspath_prepend(str(egg_path))\n return egg_path\n\n return inner\n\n\n@pytest.fixture\ndef purge_module(request):\n def inner(name):\n request.addfinalizer(lambda: sys.modules.pop(name, None))\n\n return inner\n"},{"col":4,"comment":"Can be overridden by a subclass to hook into the matching\n of the request.\n ","endLoc":370,"header":"def match_request(self) -> None","id":761,"name":"match_request","nodeType":"Function","startLoc":362,"text":"def match_request(self) -> None:\n \"\"\"Can be overridden by a subclass to hook into the matching\n of the request.\n \"\"\"\n try:\n result = self.url_adapter.match(return_rule=True) # type: ignore\n self.request.url_rule, self.request.view_args = result # type: ignore\n except HTTPException as e:\n self.request.routing_exception = e"},{"col":4,"comment":"null","endLoc":348,"header":"def _load_unlocked(self)","id":762,"name":"_load_unlocked","nodeType":"Function","startLoc":344,"text":"def _load_unlocked(self):\n __traceback_hide__ = True # noqa: F841\n self._app = rv = self.loader()\n self._bg_loading_exc_info = None\n return rv"},{"col":4,"comment":"null","endLoc":335,"header":"def _load_in_background(self)","id":763,"name":"_load_in_background","nodeType":"Function","startLoc":325,"text":"def _load_in_background(self):\n def _load_app():\n __traceback_hide__ = True # noqa: F841\n with self._lock:\n try:\n self._load_unlocked()\n except Exception:\n self._bg_loading_exc_info = sys.exc_info()\n\n t = Thread(target=_load_app, args=())\n t.start()"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":40,"id":764,"name":"app","nodeType":"Attribute","startLoc":40,"text":"self.app"},{"attributeType":"Blueprint","col":8,"comment":"null","endLoc":43,"id":765,"name":"blueprint","nodeType":"Attribute","startLoc":43,"text":"self.blueprint"},{"attributeType":"null","col":8,"comment":"null","endLoc":70,"id":766,"name":"name_prefix","nodeType":"Attribute","startLoc":70,"text":"self.name_prefix"},{"col":4,"comment":"null","endLoc":342,"header":"def _flush_bg_loading_exception(self)","id":767,"name":"_flush_bg_loading_exception","nodeType":"Function","startLoc":337,"text":"def _flush_bg_loading_exception(self):\n __traceback_hide__ = True # noqa: F841\n exc_info = self._bg_loading_exc_info\n if exc_info is not None:\n self._bg_loading_exc_info = None\n raise exc_info"},{"col":4,"comment":"null","endLoc":360,"header":"def __call__(self, environ, start_response)","id":768,"name":"__call__","nodeType":"Function","startLoc":350,"text":"def __call__(self, environ, start_response):\n __traceback_hide__ = True # noqa: F841\n if self._app is not None:\n return self._app(environ, start_response)\n self._flush_bg_loading_exception()\n with self._lock:\n if self._app is not None:\n rv = self._app\n else:\n rv = self._load_unlocked()\n return rv(environ, start_response)"},{"attributeType":"null","col":8,"comment":"null","endLoc":74,"id":769,"name":"url_defaults","nodeType":"Attribute","startLoc":74,"text":"self.url_defaults"},{"className":"Flask","col":0,"comment":"null","endLoc":48,"id":770,"nodeType":"Class","startLoc":46,"text":"class Flask(_Flask):\n testing = True\n secret_key = \"test key\""},{"attributeType":"null","col":8,"comment":"null","endLoc":47,"id":771,"name":"options","nodeType":"Attribute","startLoc":47,"text":"self.options"},{"attributeType":"None","col":8,"comment":"null","endLoc":61,"id":772,"name":"subdomain","nodeType":"Attribute","startLoc":61,"text":"self.subdomain"},{"attributeType":"null","col":4,"comment":"null","endLoc":47,"id":773,"name":"testing","nodeType":"Attribute","startLoc":47,"text":"testing"},{"col":4,"comment":"Binds the request context to the current context.","endLoc":410,"header":"def push(self) -> None","id":774,"name":"push","nodeType":"Function","startLoc":372,"text":"def push(self) -> None:\n \"\"\"Binds the request context to the current context.\"\"\"\n # If an exception occurs in debug mode or if context preservation is\n # activated under exception situations exactly one context stays\n # on the stack. The rationale is that you want to access that\n # information under debug situations. However if someone forgets to\n # pop that context again we want to make sure that on the next push\n # it's invalidated, otherwise we run at risk that something leaks\n # memory. This is usually only a problem in test suite since this\n # functionality is not active in production environments.\n top = _request_ctx_stack.top\n if top is not None and top.preserved:\n top.pop(top._preserved_exc)\n\n # Before we push the request context we have to ensure that there\n # is an application context.\n app_ctx = _app_ctx_stack.top\n if app_ctx is None or app_ctx.app != self.app:\n app_ctx = self.app.app_context()\n app_ctx.push()\n self._implicit_app_ctx_stack.append(app_ctx)\n else:\n self._implicit_app_ctx_stack.append(None)\n\n _request_ctx_stack.push(self)\n\n if self.url_adapter is not None:\n self.match_request()\n\n # Open the session at the moment that the request context is available.\n # This allows a custom open_session method to use the request context.\n # Only open a new session if this is the first time the request was\n # pushed, otherwise stream_with_context loses the session.\n if self.session is None:\n session_interface = self.app.session_interface\n self.session = session_interface.open_session(self.app, self.request)\n\n if self.session is None:\n self.session = session_interface.make_null_session(self.app)"},{"attributeType":"null","col":4,"comment":"null","endLoc":48,"id":775,"name":"secret_key","nodeType":"Attribute","startLoc":48,"text":"secret_key"},{"col":0,"comment":"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n ","endLoc":35,"header":"@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ()","id":776,"name":"_standard_os_environ","nodeType":"Function","startLoc":13,"text":"@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ():\n \"\"\"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n \"\"\"\n mp = monkeypatch.MonkeyPatch()\n out = (\n (os.environ, \"FLASK_APP\", monkeypatch.notset),\n (os.environ, \"FLASK_ENV\", monkeypatch.notset),\n (os.environ, \"FLASK_DEBUG\", monkeypatch.notset),\n (os.environ, \"FLASK_RUN_FROM_CLI\", monkeypatch.notset),\n (os.environ, \"WERKZEUG_RUN_MAIN\", monkeypatch.notset),\n )\n\n for _, key, value in out:\n if value is monkeypatch.notset:\n mp.delenv(key, False)\n else:\n mp.setenv(key, value)\n\n yield out\n mp.undo()"},{"attributeType":"None","col":8,"comment":"null","endLoc":315,"id":777,"name":"_bg_loading_exc_info","nodeType":"Attribute","startLoc":315,"text":"self._bg_loading_exc_info"},{"attributeType":"null","col":8,"comment":"null","endLoc":312,"id":778,"name":"loader","nodeType":"Attribute","startLoc":312,"text":"self.loader"},{"attributeType":"null","col":8,"comment":"null","endLoc":314,"id":779,"name":"_lock","nodeType":"Attribute","startLoc":314,"text":"self._lock"},{"col":0,"comment":"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n ","endLoc":43,"header":"@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ)","id":780,"name":"_reset_os_environ","nodeType":"Function","startLoc":38,"text":"@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ):\n \"\"\"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n \"\"\"\n monkeypatch._setitem.extend(_standard_os_environ)"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":52,"id":781,"name":"app","nodeType":"Attribute","startLoc":52,"text":"self.app"},{"col":0,"comment":"Default template context processor. Injects `request`,\n `session` and `g`.\n ","endLoc":30,"header":"def _default_template_ctx_processor() -> t.Dict[str, t.Any]","id":782,"name":"_default_template_ctx_processor","nodeType":"Function","startLoc":18,"text":"def _default_template_ctx_processor() -> t.Dict[str, t.Any]:\n \"\"\"Default template context processor. Injects `request`,\n `session` and `g`.\n \"\"\"\n reqctx = _request_ctx_stack.top\n appctx = _app_ctx_stack.top\n rv = {}\n if appctx is not None:\n rv[\"g\"] = appctx.g\n if reqctx is not None:\n rv[\"request\"] = reqctx.request\n rv[\"session\"] = reqctx.session\n return rv"},{"attributeType":"null","col":17,"comment":"null","endLoc":1,"id":783,"name":"t","nodeType":"Attribute","startLoc":1,"text":"t"},{"attributeType":"null","col":34,"comment":"null","endLoc":4,"id":784,"name":"BaseEnvironment","nodeType":"Attribute","startLoc":4,"text":"BaseEnvironment"},{"col":0,"comment":"","endLoc":1,"header":"templating.py#","id":785,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n from .scaffold import Scaffold"},{"attributeType":"null","col":8,"comment":"null","endLoc":53,"id":786,"name":"first_registration","nodeType":"Attribute","startLoc":53,"text":"self.first_registration"},{"attributeType":"None","col":8,"comment":"null","endLoc":68,"id":787,"name":"url_prefix","nodeType":"Attribute","startLoc":68,"text":"self.url_prefix"},{"attributeType":"null","col":0,"comment":"null","endLoc":22,"id":788,"name":"DeferredSetupFunction","nodeType":"Attribute","startLoc":22,"text":"DeferredSetupFunction"},{"id":789,"name":"py.typed","nodeType":"TextFile","path":"src/flask","text":""},{"col":0,"comment":"","endLoc":1,"header":"blueprints.py#","id":790,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n\nDeferredSetupFunction = t.Callable[[\"BlueprintSetupState\"], t.Callable]"},{"fileName":"logging.py","filePath":"src/flask","id":791,"nodeType":"File","text":"import logging\nimport sys\nimport typing as t\n\nfrom werkzeug.local import LocalProxy\n\nfrom .globals import request\n\nif t.TYPE_CHECKING:\n from .app import Flask\n\n\n@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO:\n \"\"\"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n \"\"\"\n return request.environ[\"wsgi.errors\"] if request else sys.stderr\n\n\ndef has_level_handler(logger: logging.Logger) -> bool:\n \"\"\"Check if there is a handler in the logging chain that will handle the\n given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.\n \"\"\"\n level = logger.getEffectiveLevel()\n current = logger\n\n while current:\n if any(handler.level <= level for handler in current.handlers):\n return True\n\n if not current.propagate:\n break\n\n current = current.parent # type: ignore\n\n return False\n\n\n#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format\n#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.\ndefault_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore\ndefault_handler.setFormatter(\n logging.Formatter(\"[%(asctime)s] %(levelname)s in %(module)s: %(message)s\")\n)\n\n\ndef create_logger(app: \"Flask\") -> logging.Logger:\n \"\"\"Get the Flask app's logger and configure it if needed.\n\n The logger name will be the same as\n :attr:`app.import_name `.\n\n When :attr:`~flask.Flask.debug` is enabled, set the logger level to\n :data:`logging.DEBUG` if it is not set.\n\n If there is no handler for the logger's effective level, add a\n :class:`~logging.StreamHandler` for\n :func:`~flask.logging.wsgi_errors_stream` with a basic format.\n \"\"\"\n logger = logging.getLogger(app.name)\n\n if app.debug and not logger.level:\n logger.setLevel(logging.DEBUG)\n\n if not has_level_handler(logger):\n logger.addHandler(default_handler)\n\n return logger\n"},{"attributeType":"None","col":8,"comment":"null","endLoc":313,"id":792,"name":"_app","nodeType":"Attribute","startLoc":313,"text":"self._app"},{"className":"ScriptInfo","col":0,"comment":"Helper object to deal with Flask applications. This is usually not\n necessary to interface with as it's used internally in the dispatching\n to click. In future versions of Flask this object will most likely play\n a bigger role. Typically it's created automatically by the\n :class:`FlaskGroup` but you can also manually create it and pass it\n onwards as click object.\n ","endLoc":424,"id":793,"nodeType":"Class","startLoc":363,"text":"class ScriptInfo:\n \"\"\"Helper object to deal with Flask applications. This is usually not\n necessary to interface with as it's used internally in the dispatching\n to click. In future versions of Flask this object will most likely play\n a bigger role. Typically it's created automatically by the\n :class:`FlaskGroup` but you can also manually create it and pass it\n onwards as click object.\n \"\"\"\n\n def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path or os.environ.get(\"FLASK_APP\")\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data = {}\n self.set_debug_flag = set_debug_flag\n self._loaded_app = None\n\n def load_app(self):\n \"\"\"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n \"\"\"\n __traceback_hide__ = True # noqa: F841\n\n if self._loaded_app is not None:\n return self._loaded_app\n\n if self.create_app is not None:\n app = call_factory(self, self.create_app)\n else:\n if self.app_import_path:\n path, name = (\n re.split(r\":(?![\\\\/])\", self.app_import_path, 1) + [None]\n )[:2]\n import_name = prepare_import(path)\n app = locate_app(self, import_name, name)\n else:\n for path in (\"wsgi.py\", \"app.py\"):\n import_name = prepare_import(path)\n app = locate_app(self, import_name, None, raise_if_not_found=False)\n\n if app:\n break\n\n if not app:\n raise NoAppException(\n \"Could not locate a Flask application. You did not provide \"\n 'the \"FLASK_APP\" environment variable, and a \"wsgi.py\" or '\n '\"app.py\" module was not found in the current directory.'\n )\n\n if self.set_debug_flag:\n # Update the app's debug flag through the descriptor so that\n # other values repopulate as well.\n app.debug = get_debug_flag()\n\n self._loaded_app = app\n return app"},{"col":4,"comment":"null","endLoc":382,"header":"def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True)","id":794,"name":"__init__","nodeType":"Function","startLoc":372,"text":"def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path or os.environ.get(\"FLASK_APP\")\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data = {}\n self.set_debug_flag = set_debug_flag\n self._loaded_app = None"},{"col":0,"comment":"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n ","endLoc":23,"header":"@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO","id":795,"name":"wsgi_errors_stream","nodeType":"Function","startLoc":13,"text":"@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO:\n \"\"\"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n \"\"\"\n return request.environ[\"wsgi.errors\"] if request else sys.stderr"},{"id":796,"name":".gitignore","nodeType":"TextFile","path":"examples/tutorial","text":"venv/\n*.pyc\n__pycache__/\ninstance/\n.cache/\n.pytest_cache/\n.coverage\nhtmlcov/\ndist/\nbuild/\n*.egg-info/\n.idea/\n*.swp\n*~\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":47,"id":797,"name":"default_handler","nodeType":"Attribute","startLoc":47,"text":"default_handler"},{"id":798,"name":"cgi.rst","nodeType":"TextFile","path":"docs/deploying","text":"CGI\n===\n\nIf all other deployment methods do not work, CGI will work for sure.\nCGI is supported by all major servers but usually has a sub-optimal\nperformance.\n\nThis is also the way you can use a Flask application on Google's `App\nEngine`_, where execution happens in a CGI-like environment.\n\n.. admonition:: Watch Out\n\n Please make sure in advance that any ``app.run()`` calls you might\n have in your application file are inside an ``if __name__ ==\n '__main__':`` block or moved to a separate file. Just make sure it's\n not called because this will always start a local WSGI server which\n we do not want if we deploy that application to CGI / app engine.\n\n With CGI, you will also have to make sure that your code does not contain\n any ``print`` statements, or that ``sys.stdout`` is overridden by something\n that doesn't write into the HTTP response.\n\nCreating a `.cgi` file\n----------------------\n\nFirst you need to create the CGI application file. Let's call it\n:file:`yourapplication.cgi`::\n\n #!/usr/bin/python\n from wsgiref.handlers import CGIHandler\n from yourapplication import app\n\n CGIHandler().run(app)\n\nServer Setup\n------------\n\nUsually there are two ways to configure the server. Either just copy the\n``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to\nrewrite the URL) or let the server point to the file directly.\n\nIn Apache for example you can put something like this into the config:\n\n.. sourcecode:: apache\n\n ScriptAlias /app /path/to/the/application.cgi\n\nOn shared webhosting, though, you might not have access to your Apache config.\nIn this case, a file called ``.htaccess``, sitting in the public directory\nyou want your app to be available, works too but the ``ScriptAlias`` directive\nwon't work in that case:\n\n.. sourcecode:: apache\n\n RewriteEngine On\n RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files\n RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]\n\nFor more information consult the documentation of your webserver.\n\n.. _App Engine: https://cloud.google.com/appengine/docs/\n"},{"id":799,"name":"database.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nDefine and Access the Database\n==============================\n\nThe application will use a `SQLite`_ database to store users and posts.\nPython comes with built-in support for SQLite in the :mod:`sqlite3`\nmodule.\n\nSQLite is convenient because it doesn't require setting up a separate\ndatabase server and is built-in to Python. However, if concurrent\nrequests try to write to the database at the same time, they will slow\ndown as each write happens sequentially. Small applications won't notice\nthis. Once you become big, you may want to switch to a different\ndatabase.\n\nThe tutorial doesn't go into detail about SQL. If you are not familiar\nwith it, the SQLite docs describe the `language`_.\n\n.. _SQLite: https://sqlite.org/about.html\n.. _language: https://sqlite.org/lang.html\n\n\nConnect to the Database\n-----------------------\n\nThe first thing to do when working with a SQLite database (and most\nother Python database libraries) is to create a connection to it. Any\nqueries and operations are performed using the connection, which is\nclosed after the work is finished.\n\nIn web applications this connection is typically tied to the request. It\nis created at some point when handling a request, and closed before the\nresponse is sent.\n\n.. code-block:: python\n :caption: ``flaskr/db.py``\n\n import sqlite3\n\n import click\n from flask import current_app, g\n from flask.cli import with_appcontext\n\n\n def get_db():\n if 'db' not in g:\n g.db = sqlite3.connect(\n current_app.config['DATABASE'],\n detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = sqlite3.Row\n\n return g.db\n\n\n def close_db(e=None):\n db = g.pop('db', None)\n\n if db is not None:\n db.close()\n\n:data:`g` is a special object that is unique for each request. It is\nused to store data that might be accessed by multiple functions during\nthe request. The connection is stored and reused instead of creating a\nnew connection if ``get_db`` is called a second time in the same\nrequest.\n\n:data:`current_app` is another special object that points to the Flask\napplication handling the request. Since you used an application factory,\nthere is no application object when writing the rest of your code.\n``get_db`` will be called when the application has been created and is\nhandling a request, so :data:`current_app` can be used.\n\n:func:`sqlite3.connect` establishes a connection to the file pointed at\nby the ``DATABASE`` configuration key. This file doesn't have to exist\nyet, and won't until you initialize the database later.\n\n:class:`sqlite3.Row` tells the connection to return rows that behave\nlike dicts. This allows accessing the columns by name.\n\n``close_db`` checks if a connection was created by checking if ``g.db``\nwas set. If the connection exists, it is closed. Further down you will\ntell your application about the ``close_db`` function in the application\nfactory so that it is called after each request.\n\n\nCreate the Tables\n-----------------\n\nIn SQLite, data is stored in *tables* and *columns*. These need to be\ncreated before you can store and retrieve data. Flaskr will store users\nin the ``user`` table, and posts in the ``post`` table. Create a file\nwith the SQL commands needed to create empty tables:\n\n.. code-block:: sql\n :caption: ``flaskr/schema.sql``\n\n DROP TABLE IF EXISTS user;\n DROP TABLE IF EXISTS post;\n\n CREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT UNIQUE NOT NULL,\n password TEXT NOT NULL\n );\n\n CREATE TABLE post (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n author_id INTEGER NOT NULL,\n created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n FOREIGN KEY (author_id) REFERENCES user (id)\n );\n\nAdd the Python functions that will run these SQL commands to the\n``db.py`` file:\n\n.. code-block:: python\n :caption: ``flaskr/db.py``\n\n def init_db():\n db = get_db()\n\n with current_app.open_resource('schema.sql') as f:\n db.executescript(f.read().decode('utf8'))\n\n\n @click.command('init-db')\n @with_appcontext\n def init_db_command():\n \"\"\"Clear the existing data and create new tables.\"\"\"\n init_db()\n click.echo('Initialized the database.')\n\n:meth:`open_resource() ` opens a file relative to\nthe ``flaskr`` package, which is useful since you won't necessarily know\nwhere that location is when deploying the application later. ``get_db``\nreturns a database connection, which is used to execute the commands\nread from the file.\n\n:func:`click.command` defines a command line command called ``init-db``\nthat calls the ``init_db`` function and shows a success message to the\nuser. You can read :doc:`/cli` to learn more about writing commands.\n\n\nRegister with the Application\n-----------------------------\n\nThe ``close_db`` and ``init_db_command`` functions need to be registered\nwith the application instance; otherwise, they won't be used by the\napplication. However, since you're using a factory function, that\ninstance isn't available when writing the functions. Instead, write a\nfunction that takes an application and does the registration.\n\n.. code-block:: python\n :caption: ``flaskr/db.py``\n\n def init_app(app):\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n\n:meth:`app.teardown_appcontext() ` tells\nFlask to call that function when cleaning up after returning the\nresponse.\n\n:meth:`app.cli.add_command() ` adds a new\ncommand that can be called with the ``flask`` command.\n\nImport and call this function from the factory. Place the new code at\nthe end of the factory function before returning the app.\n\n.. code-block:: python\n :caption: ``flaskr/__init__.py``\n\n def create_app():\n app = ...\n # existing code omitted\n\n from . import db\n db.init_app(app)\n\n return app\n\n\nInitialize the Database File\n----------------------------\n\nNow that ``init-db`` has been registered with the app, it can be called\nusing the ``flask`` command, similar to the ``run`` command from the\nprevious page.\n\n.. note::\n\n If you're still running the server from the previous page, you can\n either stop the server, or run this command in a new terminal. If\n you use a new terminal, remember to change to your project directory\n and activate the env as described in :doc:`/installation`. You'll\n also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the\n previous page.\n\nRun the ``init-db`` command:\n\n.. code-block:: none\n\n $ flask init-db\n Initialized the database.\n\nThere will now be a ``flaskr.sqlite`` file in the ``instance`` folder in\nyour project.\n\nContinue to :doc:`views`.\n"},{"id":800,"name":"cli.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nCommand Line Interface\n======================\n\nInstalling Flask installs the ``flask`` script, a `Click`_ command line\ninterface, in your virtualenv. Executed from the terminal, this script gives\naccess to built-in, extension, and application-defined commands. The ``--help``\noption will give more information about any commands and options.\n\n.. _Click: https://click.palletsprojects.com/\n\n\nApplication Discovery\n---------------------\n\nThe ``flask`` command is installed by Flask, not your application; it must be\ntold where to find your application in order to use it. The ``FLASK_APP``\nenvironment variable is used to specify how to load the application.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=hello\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=hello\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"hello\"\n > flask run\n\nWhile ``FLASK_APP`` supports a variety of options for specifying your\napplication, most use cases should be simple. Here are the typical values:\n\n(nothing)\n The name \"app\" or \"wsgi\" is imported (as a \".py\" file, or package),\n automatically detecting an app (``app`` or ``application``) or\n factory (``create_app`` or ``make_app``).\n\n``FLASK_APP=hello``\n The given name is imported, automatically detecting an app (``app``\n or ``application``) or factory (``create_app`` or ``make_app``).\n\n----\n\n``FLASK_APP`` has three parts: an optional path that sets the current working\ndirectory, a Python file or dotted import path, and an optional variable\nname of the instance or factory. If the name is a factory, it can optionally\nbe followed by arguments in parentheses. The following values demonstrate these\nparts:\n\n``FLASK_APP=src/hello``\n Sets the current working directory to ``src`` then imports ``hello``.\n\n``FLASK_APP=hello.web``\n Imports the path ``hello.web``.\n\n``FLASK_APP=hello:app2``\n Uses the ``app2`` Flask instance in ``hello``.\n\n``FLASK_APP=\"hello:create_app('dev')\"``\n The ``create_app`` factory in ``hello`` is called with the string ``'dev'``\n as the argument.\n\nIf ``FLASK_APP`` is not set, the command will try to import \"app\" or\n\"wsgi\" (as a \".py\" file, or package) and try to detect an application\ninstance or factory.\n\nWithin the given import, the command looks for an application instance named\n``app`` or ``application``, then any application instance. If no instance is\nfound, the command looks for a factory function named ``create_app`` or\n``make_app`` that returns an instance.\n\nIf parentheses follow the factory name, their contents are parsed as\nPython literals and passed as arguments and keyword arguments to the\nfunction. This means that strings must still be in quotes.\n\n\nRun the Development Server\n--------------------------\n\nThe :func:`run ` command will start the development server. It\nreplaces the :meth:`Flask.run` method in most cases. ::\n\n $ flask run\n * Serving Flask app \"hello\"\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n\n.. warning:: Do not use this command to run your application in production.\n Only use the development server during development. The development server\n is provided for convenience, but is not designed to be particularly secure,\n stable, or efficient. See :doc:`/deploying/index` for how to run in production.\n\n\nOpen a Shell\n------------\n\nTo explore the data in your application, you can start an interactive Python\nshell with the :func:`shell ` command. An application\ncontext will be active, and the app instance will be imported. ::\n\n $ flask shell\n Python 3.6.2 (default, Jul 20 2017, 03:52:27)\n [GCC 7.1.1 20170630] on linux\n App: example\n Instance: /home/user/Projects/hello/instance\n >>>\n\nUse :meth:`~Flask.shell_context_processor` to add other automatic imports.\n\n\nEnvironments\n------------\n\n.. versionadded:: 1.0\n\nThe environment in which the Flask app runs is set by the\n:envvar:`FLASK_ENV` environment variable. If not set it defaults to\n``production``. The other recognized environment is ``development``.\nFlask and extensions may choose to enable behaviors based on the\nenvironment.\n\nIf the env is set to ``development``, the ``flask`` command will enable\ndebug mode and ``flask run`` will enable the interactive debugger and\nreloader.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_ENV=development\n $ flask run\n * Serving Flask app \"hello\"\n * Environment: development\n * Debug mode: on\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n * Restarting with inotify reloader\n * Debugger is active!\n * Debugger PIN: 223-456-919\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_ENV=development\n > flask run\n * Serving Flask app \"hello\"\n * Environment: development\n * Debug mode: on\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n * Restarting with inotify reloader\n * Debugger is active!\n * Debugger PIN: 223-456-919\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_ENV = \"development\"\n > flask run\n * Serving Flask app \"hello\"\n * Environment: development\n * Debug mode: on\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n * Restarting with inotify reloader\n * Debugger is active!\n * Debugger PIN: 223-456-919\n\n\nWatch Extra Files with the Reloader\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen using development mode, the reloader will trigger whenever your\nPython code or imported modules change. The reloader can watch\nadditional files with the ``--extra-files`` option, or the\n``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are\nseparated with ``:``, or ``;`` on Windows.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ flask run --extra-files file1:dirA/file2:dirB/\n # or\n $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/\n $ flask run\n * Running on http://127.0.0.1:8000/\n * Detected change in '/path/to/file1', reloading\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > flask run --extra-files file1:dirA/file2:dirB/\n # or\n > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/\n > flask run\n * Running on http://127.0.0.1:8000/\n * Detected change in '/path/to/file1', reloading\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > flask run --extra-files file1:dirA/file2:dirB/\n # or\n > $env:FLASK_RUN_EXTRA_FILES = \"file1:dirA/file2:dirB/\"\n > flask run\n * Running on http://127.0.0.1:8000/\n * Detected change in '/path/to/file1', reloading\n\n\nDebug Mode\n----------\n\nDebug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,\nas described above. If you want to control debug mode separately, use\n:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.\n\n\n.. _dotenv:\n\nEnvironment Variables From dotenv\n---------------------------------\n\nRather than setting ``FLASK_APP`` each time you open a new terminal, you can\nuse Flask's dotenv support to set environment variables automatically.\n\nIf `python-dotenv`_ is installed, running the ``flask`` command will set\nenvironment variables defined in the files :file:`.env` and :file:`.flaskenv`.\nThis can be used to avoid having to set ``FLASK_APP`` manually every time you\nopen a new terminal, and to set configuration using environment variables\nsimilar to how some deployment services work.\n\nVariables set on the command line are used over those set in :file:`.env`,\nwhich are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be\nused for public variables, such as ``FLASK_APP``, while :file:`.env` should not\nbe committed to your repository so that it can set private variables.\n\nDirectories are scanned upwards from the directory you call ``flask``\nfrom to locate the files. The current working directory will be set to the\nlocation of the file, with the assumption that that is the top level project\ndirectory.\n\nThe files are only loaded by the ``flask`` command or calling\n:meth:`~Flask.run`. If you would like to load these files when running in\nproduction, you should call :func:`~cli.load_dotenv` manually.\n\n.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n\n\nSetting Command Options\n~~~~~~~~~~~~~~~~~~~~~~~\n\nClick is configured to load default values for command options from\nenvironment variables. The variables use the pattern\n``FLASK_COMMAND_OPTION``. For example, to set the port for the run\ncommand, instead of ``flask run --port 8000``:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_RUN_PORT=8000\n $ flask run\n * Running on http://127.0.0.1:8000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_RUN_PORT=8000\n > flask run\n * Running on http://127.0.0.1:8000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_RUN_PORT = 8000\n > flask run\n * Running on http://127.0.0.1:8000/\n\nThese can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to\ncontrol default command options.\n\n\nDisable dotenv\n~~~~~~~~~~~~~~\n\nThe ``flask`` command will show a message if it detects dotenv files but\npython-dotenv is not installed.\n\n.. code-block:: bash\n\n $ flask run\n * Tip: There are .env files present. Do \"pip install python-dotenv\" to use them.\n\nYou can tell Flask not to load dotenv files even when python-dotenv is\ninstalled by setting the ``FLASK_SKIP_DOTENV`` environment variable.\nThis can be useful if you want to load them manually, or if you're using\na project runner that loads them already. Keep in mind that the\nenvironment variables must be set before the app loads or it won't\nconfigure as expected.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_SKIP_DOTENV=1\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_SKIP_DOTENV=1\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_SKIP_DOTENV = 1\n > flask run\n\n\nEnvironment Variables From virtualenv\n-------------------------------------\n\nIf you do not want to install dotenv support, you can still set environment\nvariables by adding them to the end of the virtualenv's :file:`activate`\nscript. Activating the virtualenv will set the variables.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n Unix Bash, :file:`venv/bin/activate`::\n\n $ export FLASK_APP=hello\n\n .. group-tab:: CMD\n\n Windows CMD, :file:`venv\\\\Scripts\\\\activate.bat`::\n\n > set FLASK_APP=hello\n\n .. group-tab:: Powershell\n\n Windows Powershell, :file:`venv\\\\Scripts\\\\activate.ps1`::\n\n > $env:FLASK_APP = \"hello\"\n\nIt is preferred to use dotenv support over this, since :file:`.flaskenv` can be\ncommitted to the repository so that it works automatically wherever the project\nis checked out.\n\n\nCustom Commands\n---------------\n\nThe ``flask`` command is implemented using `Click`_. See that project's\ndocumentation for full information about writing commands.\n\nThis example adds the command ``create-user`` that takes the argument\n``name``. ::\n\n import click\n from flask import Flask\n\n app = Flask(__name__)\n\n @app.cli.command(\"create-user\")\n @click.argument(\"name\")\n def create_user(name):\n ...\n\n::\n\n $ flask create-user admin\n\nThis example adds the same command, but as ``user create``, a command in a\ngroup. This is useful if you want to organize multiple related commands. ::\n\n import click\n from flask import Flask\n from flask.cli import AppGroup\n\n app = Flask(__name__)\n user_cli = AppGroup('user')\n\n @user_cli.command('create')\n @click.argument('name')\n def create_user(name):\n ...\n\n app.cli.add_command(user_cli)\n\n::\n\n $ flask user create demo\n\nSee :ref:`testing-cli` for an overview of how to test your custom\ncommands.\n\n\nRegistering Commands with Blueprints\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf your application uses blueprints, you can optionally register CLI\ncommands directly onto them. When your blueprint is registered onto your\napplication, the associated commands will be available to the ``flask``\ncommand. By default, those commands will be nested in a group matching\nthe name of the blueprint.\n\n.. code-block:: python\n\n from flask import Blueprint\n\n bp = Blueprint('students', __name__)\n\n @bp.cli.command('create')\n @click.argument('name')\n def create(name):\n ...\n\n app.register_blueprint(bp)\n\n.. code-block:: text\n\n $ flask students create alice\n\nYou can alter the group name by specifying the ``cli_group`` parameter\nwhen creating the :class:`Blueprint` object, or later with\n:meth:`app.register_blueprint(bp, cli_group='...') `.\nThe following are equivalent:\n\n.. code-block:: python\n\n bp = Blueprint('students', __name__, cli_group='other')\n # or\n app.register_blueprint(bp, cli_group='other')\n\n.. code-block:: text\n\n $ flask other create alice\n\nSpecifying ``cli_group=None`` will remove the nesting and merge the\ncommands directly to the application's level:\n\n.. code-block:: python\n\n bp = Blueprint('students', __name__, cli_group=None)\n # or\n app.register_blueprint(bp, cli_group=None)\n\n.. code-block:: text\n\n $ flask create alice\n\n\nApplication Context\n~~~~~~~~~~~~~~~~~~~\n\nCommands added using the Flask app's :attr:`~Flask.cli`\n:meth:`~cli.AppGroup.command` decorator will be executed with an application\ncontext pushed, so your command and extensions have access to the app and its\nconfiguration. If you create a command using the Click :func:`~click.command`\ndecorator instead of the Flask decorator, you can use\n:func:`~cli.with_appcontext` to get the same behavior. ::\n\n import click\n from flask.cli import with_appcontext\n\n @click.command()\n @with_appcontext\n def do_work():\n ...\n\n app.cli.add_command(do_work)\n\nIf you're sure a command doesn't need the context, you can disable it::\n\n @app.cli.command(with_appcontext=False)\n def do_work():\n ...\n\n\nPlugins\n-------\n\nFlask will automatically load commands specified in the ``flask.commands``\n`entry point`_. This is useful for extensions that want to add commands when\nthey are installed. Entry points are specified in :file:`setup.py` ::\n\n from setuptools import setup\n\n setup(\n name='flask-my-extension',\n ...,\n entry_points={\n 'flask.commands': [\n 'my-command=flask_my_extension.commands:cli'\n ],\n },\n )\n\n\n.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points\n\nInside :file:`flask_my_extension/commands.py` you can then export a Click\nobject::\n\n import click\n\n @click.command()\n def cli():\n ...\n\nOnce that package is installed in the same virtualenv as your Flask project,\nyou can run ``flask my-command`` to invoke the command.\n\n\n.. _custom-scripts:\n\nCustom Scripts\n--------------\n\nWhen you are using the app factory pattern, it may be more convenient to define\nyour own Click script. Instead of using ``FLASK_APP`` and letting Flask load\nyour application, you can create your own Click object and export it as a\n`console script`_ entry point.\n\nCreate an instance of :class:`~cli.FlaskGroup` and pass it the factory::\n\n import click\n from flask import Flask\n from flask.cli import FlaskGroup\n\n def create_app():\n app = Flask('wiki')\n # other setup\n return app\n\n @click.group(cls=FlaskGroup, create_app=create_app)\n def cli():\n \"\"\"Management script for the Wiki application.\"\"\"\n\nDefine the entry point in :file:`setup.py`::\n\n from setuptools import setup\n\n setup(\n name='flask-my-extension',\n ...,\n entry_points={\n 'console_scripts': [\n 'wiki=wiki:cli'\n ],\n },\n )\n\nInstall the application in the virtualenv in editable mode and the custom\nscript is available. Note that you don't need to set ``FLASK_APP``. ::\n\n $ pip install -e .\n $ wiki run\n\n.. admonition:: Errors in Custom Scripts\n\n When using a custom script, if you introduce an error in your\n module-level code, the reloader will fail because it can no longer\n load the entry point.\n\n The ``flask`` command, being separate from your code, does not have\n this issue and is recommended in most cases.\n\n.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts\n\n\nPyCharm Integration\n-------------------\n\nPyCharm Professional provides a special Flask run configuration. For\nthe Community Edition, we need to configure it to call the ``flask run``\nCLI command with the correct environment variables. These instructions\nshould be similar for any other IDE you might want to use.\n\nIn PyCharm, with your project open, click on *Run* from the menu bar and\ngo to *Edit Configurations*. You'll be greeted by a screen similar to\nthis:\n\n.. image:: _static/pycharm-runconfig.png\n :align: center\n :class: screenshot\n :alt: Screenshot of PyCharms's run configuration settings.\n\nThere's quite a few options to change, but once we've done it for one\ncommand, we can easily copy the entire configuration and make a single\ntweak to give us access to other commands, including any custom ones you\nmay implement yourself.\n\nClick the + (*Add New Configuration*) button and select *Python*. Give\nthe configuration a name such as \"flask run\". For the ``flask run``\ncommand, check \"Single instance only\" since you can't run the server\nmore than once at the same time.\n\nSelect *Module name* from the dropdown (**A**) then input ``flask``.\n\nThe *Parameters* field (**B**) is set to the CLI command to execute\n(with any arguments). In this example we use ``run``, which will run\nthe development server.\n\nYou can skip this next step if you're using :ref:`dotenv`. We need to\nadd an environment variable (**C**) to identify our application. Click\non the browse button and add an entry with ``FLASK_APP`` on the left and\nthe Python import or file on the right (``hello`` for example). Add an\nentry with ``FLASK_ENV`` and set it to ``development``.\n\nNext we need to set the working directory (**D**) to be the folder where\nour application resides.\n\nIf you have installed your project as a package in your virtualenv, you\nmay untick the *PYTHONPATH* options (**E**). This will more accurately\nmatch how you deploy the app later.\n\nClick *Apply* to save the configuration, or *OK* to save and close the\nwindow. Select the configuration in the main PyCharm window and click\nthe play button next to it to run the server.\n\nNow that we have a configuration which runs ``flask run`` from within\nPyCharm, we can copy that configuration and alter the *Script* argument\nto run a different CLI command, e.g. ``flask shell``.\n"},{"id":801,"name":"api.rst","nodeType":"TextFile","path":"docs","text":"API\n===\n\n.. module:: flask\n\nThis part of the documentation covers all the interfaces of Flask. For\nparts where Flask depends on external libraries, we document the most\nimportant right here and provide links to the canonical documentation.\n\n\nApplication Object\n------------------\n\n.. autoclass:: Flask\n :members:\n :inherited-members:\n\n\nBlueprint Objects\n-----------------\n\n.. autoclass:: Blueprint\n :members:\n :inherited-members:\n\nIncoming Request Data\n---------------------\n\n.. autoclass:: Request\n :members:\n :inherited-members:\n :exclude-members: json_module\n\n.. attribute:: request\n\n To access incoming request data, you can use the global `request`\n object. Flask parses incoming request data for you and gives you\n access to it through that global object. Internally Flask makes\n sure that you always get the correct data for the active thread if you\n are in a multithreaded environment.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n The request object is an instance of a :class:`~flask.Request`.\n\n\nResponse Objects\n----------------\n\n.. autoclass:: flask.Response\n :members:\n :inherited-members:\n :exclude-members: json_module\n\nSessions\n--------\n\nIf you have set :attr:`Flask.secret_key` (or configured it from\n:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes\nit possible to remember information from one request to another. The way Flask\ndoes this is by using a signed cookie. The user can look at the session\ncontents, but can't modify it unless they know the secret key, so make sure to\nset that to something complex and unguessable.\n\nTo access the current session you can use the :class:`session` object:\n\n.. class:: session\n\n The session object works pretty much like an ordinary dict, with the\n difference that it keeps track of modifications.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n The following attributes are interesting:\n\n .. attribute:: new\n\n ``True`` if the session is new, ``False`` otherwise.\n\n .. attribute:: modified\n\n ``True`` if the session object detected a modification. Be advised\n that modifications on mutable structures are not picked up\n automatically, in that situation you have to explicitly set the\n attribute to ``True`` yourself. Here an example::\n\n # this change is not picked up because a mutable object (here\n # a list) is changed.\n session['objects'].append(42)\n # so mark it as modified yourself\n session.modified = True\n\n .. attribute:: permanent\n\n If set to ``True`` the session lives for\n :attr:`~flask.Flask.permanent_session_lifetime` seconds. The\n default is 31 days. If set to ``False`` (which is the default) the\n session will be deleted when the user closes the browser.\n\n\nSession Interface\n-----------------\n\n.. versionadded:: 0.8\n\nThe session interface provides a simple way to replace the session\nimplementation that Flask is using.\n\n.. currentmodule:: flask.sessions\n\n.. autoclass:: SessionInterface\n :members:\n\n.. autoclass:: SecureCookieSessionInterface\n :members:\n\n.. autoclass:: SecureCookieSession\n :members:\n\n.. autoclass:: NullSession\n :members:\n\n.. autoclass:: SessionMixin\n :members:\n\n.. admonition:: Notice\n\n The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer\n starting with Flask 0.8. Either catch this down yourself or use\n the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the\n app which converts the result to an integer automatically.\n\n\nTest Client\n-----------\n\n.. currentmodule:: flask.testing\n\n.. autoclass:: FlaskClient\n :members:\n\n\nTest CLI Runner\n---------------\n\n.. currentmodule:: flask.testing\n\n.. autoclass:: FlaskCliRunner\n :members:\n\n\nApplication Globals\n-------------------\n\n.. currentmodule:: flask\n\nTo share data that is valid for one request only from one function to\nanother, a global variable is not good enough because it would break in\nthreaded environments. Flask provides you with a special object that\nensures it is only valid for the active request and that will return\ndifferent values for each request. In a nutshell: it does the right\nthing, like it does for :class:`request` and :class:`session`.\n\n.. data:: g\n\n A namespace object that can store data during an\n :doc:`application context `. This is an instance of\n :attr:`Flask.app_ctx_globals_class`, which defaults to\n :class:`ctx._AppCtxGlobals`.\n\n This is a good place to store resources during a request. During\n testing, you can use the :ref:`faking-resources` pattern to\n pre-configure such resources.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n .. versionchanged:: 0.10\n Bound to the application context instead of the request context.\n\n.. autoclass:: flask.ctx._AppCtxGlobals\n :members:\n\n\nUseful Functions and Classes\n----------------------------\n\n.. data:: current_app\n\n A proxy to the application handling the current request. This is\n useful to access the application without needing to import it, or if\n it can't be imported, such as when using the application factory\n pattern or in blueprints and extensions.\n\n This is only available when an\n :doc:`application context ` is pushed. This happens\n automatically during requests and CLI commands. It can be controlled\n manually with :meth:`~flask.Flask.app_context`.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n.. autofunction:: has_request_context\n\n.. autofunction:: copy_current_request_context\n\n.. autofunction:: has_app_context\n\n.. autofunction:: url_for\n\n.. autofunction:: abort\n\n.. autofunction:: redirect\n\n.. autofunction:: make_response\n\n.. autofunction:: after_this_request\n\n.. autofunction:: send_file\n\n.. autofunction:: send_from_directory\n\n.. autofunction:: safe_join\n\n.. autofunction:: escape\n\n.. autoclass:: Markup\n :members: escape, unescape, striptags\n\nMessage Flashing\n----------------\n\n.. autofunction:: flash\n\n.. autofunction:: get_flashed_messages\n\n\nJSON Support\n------------\n\n.. module:: flask.json\n\nFlask uses the built-in :mod:`json` module for handling JSON. It will\nuse the current blueprint's or application's JSON encoder and decoder\nfor easier customization. By default it handles some extra data types:\n\n- :class:`datetime.datetime` and :class:`datetime.date` are serialized\n to :rfc:`822` strings. This is the same as the HTTP date format.\n- :class:`uuid.UUID` is serialized to a string.\n- :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n- :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n\nJinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`\nfunction. The filter marks the output with ``|safe`` automatically. Use\nthe filter to render data inside ``\n\n.. autofunction:: jsonify\n\n.. autofunction:: dumps\n\n.. autofunction:: dump\n\n.. autofunction:: loads\n\n.. autofunction:: load\n\n.. autoclass:: JSONEncoder\n :members:\n\n.. autoclass:: JSONDecoder\n :members:\n\n.. automodule:: flask.json.tag\n\n\nTemplate Rendering\n------------------\n\n.. currentmodule:: flask\n\n.. autofunction:: render_template\n\n.. autofunction:: render_template_string\n\n.. autofunction:: get_template_attribute\n\nConfiguration\n-------------\n\n.. autoclass:: Config\n :members:\n\n\nStream Helpers\n--------------\n\n.. autofunction:: stream_with_context\n\nUseful Internals\n----------------\n\n.. autoclass:: flask.ctx.RequestContext\n :members:\n\n.. data:: _request_ctx_stack\n\n The internal :class:`~werkzeug.local.LocalStack` that holds\n :class:`~flask.ctx.RequestContext` instances. Typically, the\n :data:`request` and :data:`session` proxies should be accessed\n instead of the stack. It may be useful to access the stack in\n extension code.\n\n The following attributes are always present on each layer of the\n stack:\n\n `app`\n the active Flask application.\n\n `url_adapter`\n the URL adapter that was used to match the request.\n\n `request`\n the current request object.\n\n `session`\n the active session object.\n\n `g`\n an object with all the attributes of the :data:`flask.g` object.\n\n `flashes`\n an internal cache for the flashed messages.\n\n Example usage::\n\n from flask import _request_ctx_stack\n\n def get_session():\n ctx = _request_ctx_stack.top\n if ctx is not None:\n return ctx.session\n\n.. autoclass:: flask.ctx.AppContext\n :members:\n\n.. data:: _app_ctx_stack\n\n The internal :class:`~werkzeug.local.LocalStack` that holds\n :class:`~flask.ctx.AppContext` instances. Typically, the\n :data:`current_app` and :data:`g` proxies should be accessed instead\n of the stack. Extensions can access the contexts on the stack as a\n namespace to store data.\n\n .. versionadded:: 0.9\n\n.. autoclass:: flask.blueprints.BlueprintSetupState\n :members:\n\n.. _core-signals-list:\n\nSignals\n-------\n\n.. versionadded:: 0.6\n\n.. data:: signals.signals_available\n\n ``True`` if the signaling system is available. This is the case\n when `blinker`_ is installed.\n\nThe following signals exist in Flask:\n\n.. data:: template_rendered\n\n This signal is sent when a template was successfully rendered. The\n signal is invoked with the instance of the template as `template`\n and the context as dictionary (named `context`).\n\n Example subscriber::\n\n def log_template_renders(sender, template, context, **extra):\n sender.logger.debug('Rendering template \"%s\" with context %s',\n template.name or 'string template',\n context)\n\n from flask import template_rendered\n template_rendered.connect(log_template_renders, app)\n\n.. data:: flask.before_render_template\n :noindex:\n\n This signal is sent before template rendering process. The\n signal is invoked with the instance of the template as `template`\n and the context as dictionary (named `context`).\n\n Example subscriber::\n\n def log_template_renders(sender, template, context, **extra):\n sender.logger.debug('Rendering template \"%s\" with context %s',\n template.name or 'string template',\n context)\n\n from flask import before_render_template\n before_render_template.connect(log_template_renders, app)\n\n.. data:: request_started\n\n This signal is sent when the request context is set up, before\n any request processing happens. Because the request context is already\n bound, the subscriber can access the request with the standard global\n proxies such as :class:`~flask.request`.\n\n Example subscriber::\n\n def log_request(sender, **extra):\n sender.logger.debug('Request context is set up')\n\n from flask import request_started\n request_started.connect(log_request, app)\n\n.. data:: request_finished\n\n This signal is sent right before the response is sent to the client.\n It is passed the response to be sent named `response`.\n\n Example subscriber::\n\n def log_response(sender, response, **extra):\n sender.logger.debug('Request context is about to close down. '\n 'Response: %s', response)\n\n from flask import request_finished\n request_finished.connect(log_response, app)\n\n.. data:: got_request_exception\n\n This signal is sent when an unhandled exception happens during\n request processing, including when debugging. The exception is\n passed to the subscriber as ``exception``.\n\n This signal is not sent for\n :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that\n have error handlers registered, unless the exception was raised from\n an error handler.\n\n This example shows how to do some extra logging if a theoretical\n ``SecurityException`` was raised:\n\n .. code-block:: python\n\n from flask import got_request_exception\n\n def log_security_exception(sender, exception, **extra):\n if not isinstance(exception, SecurityException):\n return\n\n security_logger.exception(\n f\"SecurityException at {request.url!r}\",\n exc_info=exception,\n )\n\n got_request_exception.connect(log_security_exception, app)\n\n.. data:: request_tearing_down\n\n This signal is sent when the request is tearing down. This is always\n called, even if an exception is caused. Currently functions listening\n to this signal are called after the regular teardown handlers, but this\n is not something you can rely on.\n\n Example subscriber::\n\n def close_db_connection(sender, **extra):\n session.close()\n\n from flask import request_tearing_down\n request_tearing_down.connect(close_db_connection, app)\n\n As of Flask 0.9, this will also be passed an `exc` keyword argument\n that has a reference to the exception that caused the teardown if\n there was one.\n\n.. data:: appcontext_tearing_down\n\n This signal is sent when the app context is tearing down. This is always\n called, even if an exception is caused. Currently functions listening\n to this signal are called after the regular teardown handlers, but this\n is not something you can rely on.\n\n Example subscriber::\n\n def close_db_connection(sender, **extra):\n session.close()\n\n from flask import appcontext_tearing_down\n appcontext_tearing_down.connect(close_db_connection, app)\n\n This will also be passed an `exc` keyword argument that has a reference\n to the exception that caused the teardown if there was one.\n\n.. data:: appcontext_pushed\n\n This signal is sent when an application context is pushed. The sender\n is the application. This is usually useful for unittests in order to\n temporarily hook in information. For instance it can be used to\n set a resource early onto the `g` object.\n\n Example usage::\n\n from contextlib import contextmanager\n from flask import appcontext_pushed\n\n @contextmanager\n def user_set(app, user):\n def handler(sender, **kwargs):\n g.user = user\n with appcontext_pushed.connected_to(handler, app):\n yield\n\n And in the testcode::\n\n def test_user_me(self):\n with user_set(app, 'john'):\n c = app.test_client()\n resp = c.get('/users/me')\n assert resp.data == 'username=john'\n\n .. versionadded:: 0.10\n\n.. data:: appcontext_popped\n\n This signal is sent when an application context is popped. The sender\n is the application. This usually falls in line with the\n :data:`appcontext_tearing_down` signal.\n\n .. versionadded:: 0.10\n\n\n.. data:: message_flashed\n\n This signal is sent when the application is flashing a message. The\n messages is sent as `message` keyword argument and the category as\n `category`.\n\n Example subscriber::\n\n recorded = []\n def record(sender, message, category, **extra):\n recorded.append((message, category))\n\n from flask import message_flashed\n message_flashed.connect(record, app)\n\n .. versionadded:: 0.10\n\n.. class:: signals.Namespace\n\n An alias for :class:`blinker.base.Namespace` if blinker is available,\n otherwise a dummy class that creates fake signals. This class is\n available for Flask extensions that want to provide the same fallback\n system as Flask itself.\n\n .. method:: signal(name, doc=None)\n\n Creates a new signal for this namespace if blinker is available,\n otherwise returns a fake signal that has a send method that will\n do nothing but will fail with a :exc:`RuntimeError` for all other\n operations, including connecting.\n\n\n.. _blinker: https://pypi.org/project/blinker/\n\n\nClass-Based Views\n-----------------\n\n.. versionadded:: 0.7\n\n.. currentmodule:: None\n\n.. autoclass:: flask.views.View\n :members:\n\n.. autoclass:: flask.views.MethodView\n :members:\n\n.. _url-route-registrations:\n\nURL Route Registrations\n-----------------------\n\nGenerally there are three ways to define rules for the routing system:\n\n1. You can use the :meth:`flask.Flask.route` decorator.\n2. You can use the :meth:`flask.Flask.add_url_rule` function.\n3. You can directly access the underlying Werkzeug routing system\n which is exposed as :attr:`flask.Flask.url_map`.\n\nVariable parts in the route can be specified with angular brackets\n(``/user/``). By default a variable part in the URL accepts any\nstring without a slash however a different converter can be specified as\nwell by using ````.\n\nVariable parts are passed to the view function as keyword arguments.\n\nThe following converters are available:\n\n=========== ===============================================\n`string` accepts any text without a slash (the default)\n`int` accepts integers\n`float` like `int` but for floating point values\n`path` like the default but also accepts slashes\n`any` matches one of the items provided\n`uuid` accepts UUID strings\n=========== ===============================================\n\nCustom converters can be defined using :attr:`flask.Flask.url_map`.\n\nHere are some examples::\n\n @app.route('/')\n def index():\n pass\n\n @app.route('/')\n def show_user(username):\n pass\n\n @app.route('/post/')\n def show_post(post_id):\n pass\n\nAn important detail to keep in mind is how Flask deals with trailing\nslashes. The idea is to keep each URL unique so the following rules\napply:\n\n1. If a rule ends with a slash and is requested without a slash by the\n user, the user is automatically redirected to the same page with a\n trailing slash attached.\n2. If a rule does not end with a trailing slash and the user requests the\n page with a trailing slash, a 404 not found is raised.\n\nThis is consistent with how web servers deal with static files. This\nalso makes it possible to use relative link targets safely.\n\nYou can also define multiple rules for the same function. They have to be\nunique however. Defaults can also be specified. Here for example is a\ndefinition for a URL that accepts an optional page::\n\n @app.route('/users/', defaults={'page': 1})\n @app.route('/users/page/')\n def show_users(page):\n pass\n\nThis specifies that ``/users/`` will be the URL for page one and\n``/users/page/N`` will be the URL for page ``N``.\n\nIf a URL contains a default value, it will be redirected to its simpler\nform with a 301 redirect. In the above example, ``/users/page/1`` will\nbe redirected to ``/users/``. If your route handles ``GET`` and ``POST``\nrequests, make sure the default route only handles ``GET``, as redirects\ncan't preserve form data. ::\n\n @app.route('/region/', defaults={'id': 1})\n @app.route('/region/', methods=['GET', 'POST'])\n def region(id):\n pass\n\nHere are the parameters that :meth:`~flask.Flask.route` and\n:meth:`~flask.Flask.add_url_rule` accept. The only difference is that\nwith the route parameter the view function is defined with the decorator\ninstead of the `view_func` parameter.\n\n=============== ==========================================================\n`rule` the URL rule as string\n`endpoint` the endpoint for the registered URL rule. Flask itself\n assumes that the name of the view function is the name\n of the endpoint if not explicitly stated.\n`view_func` the function to call when serving a request to the\n provided endpoint. If this is not provided one can\n specify the function later by storing it in the\n :attr:`~flask.Flask.view_functions` dictionary with the\n endpoint as key.\n`defaults` A dictionary with defaults for this rule. See the\n example above for how defaults work.\n`subdomain` specifies the rule for the subdomain in case subdomain\n matching is in use. If not specified the default\n subdomain is assumed.\n`**options` the options to be forwarded to the underlying\n :class:`~werkzeug.routing.Rule` object. A change to\n Werkzeug is handling of method options. methods is a list\n of methods this rule should be limited to (``GET``, ``POST``\n etc.). By default a rule just listens for ``GET`` (and\n implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is\n implicitly added and handled by the standard request\n handling. They have to be specified as keyword arguments.\n=============== ==========================================================\n\n\nView Function Options\n---------------------\n\nFor internal usage the view functions can have some attributes attached to\ncustomize behavior the view function would normally not have control over.\nThe following attributes can be provided optionally to either override\nsome defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:\n\n- `__name__`: The name of a function is by default used as endpoint. If\n endpoint is provided explicitly this value is used. Additionally this\n will be prefixed with the name of the blueprint by default which\n cannot be customized from the function itself.\n\n- `methods`: If methods are not provided when the URL rule is added,\n Flask will look on the view function object itself if a `methods`\n attribute exists. If it does, it will pull the information for the\n methods from there.\n\n- `provide_automatic_options`: if this attribute is set Flask will\n either force enable or disable the automatic implementation of the\n HTTP ``OPTIONS`` response. This can be useful when working with\n decorators that want to customize the ``OPTIONS`` response on a per-view\n basis.\n\n- `required_methods`: if this attribute is set, Flask will always add\n these methods when registering a URL rule even if the methods were\n explicitly overridden in the ``route()`` call.\n\nFull example::\n\n def index():\n if request.method == 'OPTIONS':\n # custom options handling here\n ...\n return 'Hello World!'\n index.provide_automatic_options = False\n index.methods = ['GET', 'OPTIONS']\n\n app.add_url_rule('/', index)\n\n.. versionadded:: 0.8\n The `provide_automatic_options` functionality was added.\n\nCommand Line Interface\n----------------------\n\n.. currentmodule:: flask.cli\n\n.. autoclass:: FlaskGroup\n :members:\n\n.. autoclass:: AppGroup\n :members:\n\n.. autoclass:: ScriptInfo\n :members:\n\n.. autofunction:: load_dotenv\n\n.. autofunction:: with_appcontext\n\n.. autofunction:: pass_script_info\n\n Marks a function so that an instance of :class:`ScriptInfo` is passed\n as first argument to the click callback.\n\n.. autodata:: run_command\n\n.. autodata:: shell_command\n"},{"id":802,"name":"asgi.rst","nodeType":"TextFile","path":"docs/deploying","text":".. _asgi:\n\nASGI\n====\n\nIf you'd like to use an ASGI server you will need to utilise WSGI to\nASGI middleware. The asgiref\n[WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter)\nadapter is recommended as it integrates with the event loop used for\nFlask's :ref:`async_await` support. You can use the adapter by\nwrapping the Flask app,\n\n.. code-block:: python\n\n from asgiref.wsgi import WsgiToAsgi\n from flask import Flask\n\n app = Flask(__name__)\n\n ...\n\n asgi_app = WsgiToAsgi(app)\n\nand then serving the ``asgi_app`` with the asgi server, e.g. using\n`Hypercorn `_,\n\n.. sourcecode:: text\n\n $ hypercorn module:asgi_app\n"},{"col":0,"comment":"","endLoc":1,"header":"logging.py#","id":803,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n\ndefault_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore\n\ndefault_handler.setFormatter(\n logging.Formatter(\"[%(asctime)s] %(levelname)s in %(module)s: %(message)s\")\n)"},{"id":804,"name":"index.rst","nodeType":"TextFile","path":"docs","text":".. rst-class:: hide-header\n\nWelcome to Flask\n================\n\n.. image:: _static/flask-logo.png\n :alt: Flask: web development, one drop at a time\n :align: center\n :target: https://palletsprojects.com/p/flask/\n\nWelcome to Flask's documentation. Get started with :doc:`installation`\nand then get an overview with the :doc:`quickstart`. There is also a\nmore detailed :doc:`tutorial/index` that shows how to create a small but\ncomplete application with Flask. Common patterns are described in the\n:doc:`patterns/index` section. The rest of the docs describe each\ncomponent of Flask in detail, with a full reference in the :doc:`api`\nsection.\n\nFlask depends on the `Jinja`_ template engine and the `Werkzeug`_ WSGI\ntoolkit. The documentation for these libraries can be found at:\n\n- `Jinja documentation `_\n- `Werkzeug documentation `_\n\n.. _Jinja: https://www.palletsprojects.com/p/jinja/\n.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/\n\n\nUser's Guide\n------------\n\nThis part of the documentation, which is mostly prose, begins with some\nbackground information about Flask, then focuses on step-by-step\ninstructions for web development with Flask.\n\n.. toctree::\n :maxdepth: 2\n\n foreword\n advanced_foreword\n installation\n quickstart\n tutorial/index\n templating\n testing\n errorhandling\n debugging\n logging\n config\n signals\n views\n appcontext\n reqcontext\n blueprints\n extensions\n cli\n server\n shell\n patterns/index\n deploying/index\n becomingbig\n async-await\n\n\nAPI Reference\n-------------\n\nIf you are looking for information on a specific function, class or\nmethod, this part of the documentation is for you.\n\n.. toctree::\n :maxdepth: 2\n\n api\n\n\nAdditional Notes\n----------------\n\nDesign notes, legal information and changelog are here for the interested.\n\n.. toctree::\n :maxdepth: 2\n\n design\n htmlfaq\n security\n extensiondev\n contributing\n license\n changes\n"},{"id":805,"name":"installation.rst","nodeType":"TextFile","path":"docs","text":"Installation\n============\n\n\nPython Version\n--------------\n\nWe recommend using the latest version of Python. Flask supports Python\n3.6 and newer.\n\n\nDependencies\n------------\n\nThese distributions will be installed automatically when installing Flask.\n\n* `Werkzeug`_ implements WSGI, the standard Python interface between\n applications and servers.\n* `Jinja`_ is a template language that renders the pages your application\n serves.\n* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering\n templates to avoid injection attacks.\n* `ItsDangerous`_ securely signs data to ensure its integrity. This is used\n to protect Flask's session cookie.\n* `Click`_ is a framework for writing command line applications. It provides\n the ``flask`` command and allows adding custom management commands.\n\n.. _Werkzeug: https://palletsprojects.com/p/werkzeug/\n.. _Jinja: https://palletsprojects.com/p/jinja/\n.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/\n.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/\n.. _Click: https://palletsprojects.com/p/click/\n\n\nOptional dependencies\n~~~~~~~~~~~~~~~~~~~~~\n\nThese distributions will not be installed automatically. Flask will detect and\nuse them if you install them.\n\n* `Blinker`_ provides support for :doc:`signals`.\n* `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``\n commands.\n* `Watchdog`_ provides a faster, more efficient reloader for the development\n server.\n\n.. _Blinker: https://pythonhosted.org/blinker/\n.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n.. _watchdog: https://pythonhosted.org/watchdog/\n\n\nVirtual environments\n--------------------\n\nUse a virtual environment to manage the dependencies for your project, both in\ndevelopment and in production.\n\nWhat problem does a virtual environment solve? The more Python projects you\nhave, the more likely it is that you need to work with different versions of\nPython libraries, or even Python itself. Newer versions of libraries for one\nproject can break compatibility in another project.\n\nVirtual environments are independent groups of Python libraries, one for each\nproject. Packages installed for one project will not affect other projects or\nthe operating system's packages.\n\nPython comes bundled with the :mod:`venv` module to create virtual\nenvironments.\n\n\n.. _install-create-env:\n\nCreate an environment\n~~~~~~~~~~~~~~~~~~~~~\n\nCreate a project folder and a :file:`venv` folder within:\n\n.. tabs::\n\n .. group-tab:: macOS/Linux\n\n .. code-block:: text\n\n $ mkdir myproject\n $ cd myproject\n $ python3 -m venv venv\n\n .. group-tab:: Windows\n\n .. code-block:: text\n\n > mkdir myproject\n > cd myproject\n > py -3 -m venv venv\n\n\n.. _install-activate-env:\n\nActivate the environment\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore you work on your project, activate the corresponding environment:\n\n.. tabs::\n\n .. group-tab:: macOS/Linux\n\n .. code-block:: text\n\n $ . venv/bin/activate\n\n .. group-tab:: Windows\n\n .. code-block:: text\n\n > venv\\Scripts\\activate\n\nYour shell prompt will change to show the name of the activated\nenvironment.\n\n\nInstall Flask\n-------------\n\nWithin the activated environment, use the following command to install\nFlask:\n\n.. code-block:: sh\n\n $ pip install Flask\n\nFlask is now installed. Check out the :doc:`/quickstart` or go to the\n:doc:`Documentation Overview `.\n"},{"id":806,"name":"license.rst","nodeType":"TextFile","path":"docs","text":"License\n=======\n\nBSD-3-Clause Source License\n---------------------------\n\nThe BSD-3-Clause license applies to all files in the Flask repository\nand source distribution. This includes Flask's source code, the\nexamples, and tests, as well as the documentation.\n\n.. include:: ../LICENSE.rst\n\n\nArtwork License\n---------------\n\nThis license applies to Flask's logo.\n\n.. include:: ../artwork/LICENSE.rst\n"},{"id":807,"name":"config.rst","nodeType":"TextFile","path":"docs","text":"Configuration Handling\n======================\n\nApplications need some kind of configuration. There are different settings\nyou might want to change depending on the application environment like\ntoggling the debug mode, setting the secret key, and other such\nenvironment-specific things.\n\nThe way Flask is designed usually requires the configuration to be\navailable when the application starts up. You can hard code the\nconfiguration in the code, which for many small applications is not\nactually that bad, but there are better ways.\n\nIndependent of how you load your config, there is a config object\navailable which holds the loaded configuration values:\nThe :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`\nobject. This is the place where Flask itself puts certain configuration\nvalues and also where extensions can put their configuration values. But\nthis is also where you can have your own configuration.\n\n\nConfiguration Basics\n--------------------\n\nThe :attr:`~flask.Flask.config` is actually a subclass of a dictionary and\ncan be modified just like any dictionary::\n\n app = Flask(__name__)\n app.config['TESTING'] = True\n\nCertain configuration values are also forwarded to the\n:attr:`~flask.Flask` object so you can read and write them from there::\n\n app.testing = True\n\nTo update multiple keys at once you can use the :meth:`dict.update`\nmethod::\n\n app.config.update(\n TESTING=True,\n SECRET_KEY=b'_5#y2L\"F4Q8z\\n\\xec]/'\n )\n\n\nEnvironment and Debug Features\n------------------------------\n\nThe :data:`ENV` and :data:`DEBUG` config values are special because they\nmay behave inconsistently if changed after the app has begun setting up.\nIn order to set the environment and debug mode reliably, Flask uses\nenvironment variables.\n\nThe environment is used to indicate to Flask, extensions, and other\nprograms, like Sentry, what context Flask is running in. It is\ncontrolled with the :envvar:`FLASK_ENV` environment variable and\ndefaults to ``production``.\n\nSetting :envvar:`FLASK_ENV` to ``development`` will enable debug mode.\n``flask run`` will use the interactive debugger and reloader by default\nin debug mode. To control this separately from the environment, use the\n:envvar:`FLASK_DEBUG` flag.\n\n.. versionchanged:: 1.0\n Added :envvar:`FLASK_ENV` to control the environment separately\n from debug mode. The development environment enables debug mode.\n\nTo switch Flask to the development environment and enable debug mode,\nset :envvar:`FLASK_ENV`:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_ENV=development\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_ENV=development\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_ENV = \"development\"\n > flask run\n\nUsing the environment variables as described above is recommended. While\nit is possible to set :data:`ENV` and :data:`DEBUG` in your config or\ncode, this is strongly discouraged. They can't be read early by the\n``flask`` command, and some systems or extensions may have already\nconfigured themselves based on a previous value.\n\n\nBuiltin Configuration Values\n----------------------------\n\nThe following configuration values are used internally by Flask:\n\n.. py:data:: ENV\n\n What environment the app is running in. Flask and extensions may\n enable behaviors based on the environment, such as enabling debug\n mode. The :attr:`~flask.Flask.env` attribute maps to this config\n key. This is set by the :envvar:`FLASK_ENV` environment variable and\n may not behave as expected if set in code.\n\n **Do not enable development when deploying in production.**\n\n Default: ``'production'``\n\n .. versionadded:: 1.0\n\n.. py:data:: DEBUG\n\n Whether debug mode is enabled. When using ``flask run`` to start the\n development server, an interactive debugger will be shown for\n unhandled exceptions, and the server will be reloaded when code\n changes. The :attr:`~flask.Flask.debug` attribute maps to this\n config key. This is enabled when :data:`ENV` is ``'development'``\n and is overridden by the ``FLASK_DEBUG`` environment variable. It\n may not behave as expected if set in code.\n\n **Do not enable debug mode when deploying in production.**\n\n Default: ``True`` if :data:`ENV` is ``'development'``, or ``False``\n otherwise.\n\n.. py:data:: TESTING\n\n Enable testing mode. Exceptions are propagated rather than handled by the\n the app's error handlers. Extensions may also change their behavior to\n facilitate easier testing. You should enable this in your own tests.\n\n Default: ``False``\n\n.. py:data:: PROPAGATE_EXCEPTIONS\n\n Exceptions are re-raised rather than being handled by the app's error\n handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``\n is enabled.\n\n Default: ``None``\n\n.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION\n\n Don't pop the request context when an exception occurs. If not set, this\n is true if ``DEBUG`` is true. This allows debuggers to introspect the\n request data on errors, and should normally not need to be set directly.\n\n Default: ``None``\n\n.. py:data:: TRAP_HTTP_EXCEPTIONS\n\n If there is no handler for an ``HTTPException``-type exception, re-raise it\n to be handled by the interactive debugger instead of returning it as a\n simple error response.\n\n Default: ``False``\n\n.. py:data:: TRAP_BAD_REQUEST_ERRORS\n\n Trying to access a key that doesn't exist from request dicts like ``args``\n and ``form`` will return a 400 Bad Request error page. Enable this to treat\n the error as an unhandled exception instead so that you get the interactive\n debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If\n unset, it is enabled in debug mode.\n\n Default: ``None``\n\n.. py:data:: SECRET_KEY\n\n A secret key that will be used for securely signing the session cookie\n and can be used for any other security related needs by extensions or your\n application. It should be a long random ``bytes`` or ``str``. For\n example, copy the output of this to your config::\n\n $ python -c 'import os; print(os.urandom(16))'\n b'_5#y2L\"F4Q8z\\n\\xec]/'\n\n **Do not reveal the secret key when posting questions or committing code.**\n\n Default: ``None``\n\n.. py:data:: SESSION_COOKIE_NAME\n\n The name of the session cookie. Can be changed in case you already have a\n cookie with the same name.\n\n Default: ``'session'``\n\n.. py:data:: SESSION_COOKIE_DOMAIN\n\n The domain match rule that the session cookie will be valid for. If not\n set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`.\n If ``False``, the cookie's domain will not be set.\n\n Default: ``None``\n\n.. py:data:: SESSION_COOKIE_PATH\n\n The path that the session cookie will be valid for. If not set, the cookie\n will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.\n\n Default: ``None``\n\n.. py:data:: SESSION_COOKIE_HTTPONLY\n\n Browsers will not allow JavaScript access to cookies marked as \"HTTP only\"\n for security.\n\n Default: ``True``\n\n.. py:data:: SESSION_COOKIE_SECURE\n\n Browsers will only send cookies with requests over HTTPS if the cookie is\n marked \"secure\". The application must be served over HTTPS for this to make\n sense.\n\n Default: ``False``\n\n.. py:data:: SESSION_COOKIE_SAMESITE\n\n Restrict how cookies are sent with requests from external sites. Can\n be set to ``'Lax'`` (recommended) or ``'Strict'``.\n See :ref:`security-cookie`.\n\n Default: ``None``\n\n .. versionadded:: 1.0\n\n.. py:data:: PERMANENT_SESSION_LIFETIME\n\n If ``session.permanent`` is true, the cookie's expiration will be set this\n number of seconds in the future. Can either be a\n :class:`datetime.timedelta` or an ``int``.\n\n Flask's default cookie implementation validates that the cryptographic\n signature is not older than this value.\n\n Default: ``timedelta(days=31)`` (``2678400`` seconds)\n\n.. py:data:: SESSION_REFRESH_EACH_REQUEST\n\n Control whether the cookie is sent with every response when\n ``session.permanent`` is true. Sending the cookie every time (the default)\n can more reliably keep the session from expiring, but uses more bandwidth.\n Non-permanent sessions are not affected.\n\n Default: ``True``\n\n.. py:data:: USE_X_SENDFILE\n\n When serving files, set the ``X-Sendfile`` header instead of serving the\n data with Flask. Some web servers, such as Apache, recognize this and serve\n the data more efficiently. This only makes sense when using such a server.\n\n Default: ``False``\n\n.. py:data:: SEND_FILE_MAX_AGE_DEFAULT\n\n When serving files, set the cache control max age to this number of\n seconds. Can be a :class:`datetime.timedelta` or an ``int``.\n Override this value on a per-file basis using\n :meth:`~flask.Flask.get_send_file_max_age` on the application or\n blueprint.\n\n If ``None``, ``send_file`` tells the browser to use conditional\n requests will be used instead of a timed cache, which is usually\n preferable.\n\n Default: ``None``\n\n.. py:data:: SERVER_NAME\n\n Inform the application what host and port it is bound to. Required\n for subdomain route matching support.\n\n If set, will be used for the session cookie domain if\n :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will\n not allow setting cookies for domains without a dot. To use a domain\n locally, add any names that should route to the app to your\n ``hosts`` file. ::\n\n 127.0.0.1 localhost.dev\n\n If set, ``url_for`` can generate external URLs with only an application\n context instead of a request context.\n\n Default: ``None``\n\n.. py:data:: APPLICATION_ROOT\n\n Inform the application what path it is mounted under by the application /\n web server. This is used for generating URLs outside the context of a\n request (inside a request, the dispatcher is responsible for setting\n ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch`\n for examples of dispatch configuration).\n\n Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not\n set.\n\n Default: ``'/'``\n\n.. py:data:: PREFERRED_URL_SCHEME\n\n Use this scheme for generating external URLs when not in a request context.\n\n Default: ``'http'``\n\n.. py:data:: MAX_CONTENT_LENGTH\n\n Don't read more than this many bytes from the incoming request data. If not\n set and the request does not specify a ``CONTENT_LENGTH``, no data will be\n read for security.\n\n Default: ``None``\n\n.. py:data:: JSON_AS_ASCII\n\n Serialize objects to ASCII-encoded JSON. If this is disabled, the\n JSON returned from ``jsonify`` will contain Unicode characters. This\n has security implications when rendering the JSON into JavaScript in\n templates, and should typically remain enabled.\n\n Default: ``True``\n\n.. py:data:: JSON_SORT_KEYS\n\n Sort the keys of JSON objects alphabetically. This is useful for caching\n because it ensures the data is serialized the same way no matter what\n Python's hash seed is. While not recommended, you can disable this for a\n possible performance improvement at the cost of caching.\n\n Default: ``True``\n\n.. py:data:: JSONIFY_PRETTYPRINT_REGULAR\n\n ``jsonify`` responses will be output with newlines, spaces, and indentation\n for easier reading by humans. Always enabled in debug mode.\n\n Default: ``False``\n\n.. py:data:: JSONIFY_MIMETYPE\n\n The mimetype of ``jsonify`` responses.\n\n Default: ``'application/json'``\n\n.. py:data:: TEMPLATES_AUTO_RELOAD\n\n Reload templates when they are changed. If not set, it will be enabled in\n debug mode.\n\n Default: ``None``\n\n.. py:data:: EXPLAIN_TEMPLATE_LOADING\n\n Log debugging information tracing how a template file was loaded. This can\n be useful to figure out why a template was not loaded or the wrong file\n appears to be loaded.\n\n Default: ``False``\n\n.. py:data:: MAX_COOKIE_SIZE\n\n Warn if cookie headers are larger than this many bytes. Defaults to\n ``4093``. Larger cookies may be silently ignored by browsers. Set to\n ``0`` to disable the warning.\n\n.. versionadded:: 0.4\n ``LOGGER_NAME``\n\n.. versionadded:: 0.5\n ``SERVER_NAME``\n\n.. versionadded:: 0.6\n ``MAX_CONTENT_LENGTH``\n\n.. versionadded:: 0.7\n ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``\n\n.. versionadded:: 0.8\n ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,\n ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,\n ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,\n ``SESSION_COOKIE_SECURE``\n\n.. versionadded:: 0.9\n ``PREFERRED_URL_SCHEME``\n\n.. versionadded:: 0.10\n ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``\n\n.. versionadded:: 0.11\n ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,\n ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``\n\n.. versionchanged:: 1.0\n ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See\n :doc:`/logging` for information about configuration.\n\n Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment\n variable.\n\n Added :data:`SESSION_COOKIE_SAMESITE` to control the session\n cookie's ``SameSite`` option.\n\n Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.\n\n\nConfiguring from Python Files\n-----------------------------\n\nConfiguration becomes more useful if you can store it in a separate file,\nideally located outside the actual application package. This makes\npackaging and distributing your application possible via various package\nhandling tools (:doc:`/patterns/distribute`) and finally modifying the\nconfiguration file afterwards.\n\nSo a common pattern is this::\n\n app = Flask(__name__)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\nThis first loads the configuration from the\n`yourapplication.default_settings` module and then overrides the values\nwith the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`\nenvironment variable points to. This environment variable can be set\nin the shell before starting the server:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set YOURAPPLICATION_SETTINGS=\\path\\to\\settings.cfg\n > flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:YOURAPPLICATION_SETTINGS = \"\\path\\to\\settings.cfg\"\n > flask run\n * Running on http://127.0.0.1:5000/\n\nThe configuration files themselves are actual Python files. Only values\nin uppercase are actually stored in the config object later on. So make\nsure to use uppercase letters for your config keys.\n\nHere is an example of a configuration file::\n\n # Example configuration\n SECRET_KEY = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\nMake sure to load the configuration very early on, so that extensions have\nthe ability to access the configuration when starting up. There are other\nmethods on the config object as well to load from individual files. For a\ncomplete reference, read the :class:`~flask.Config` object's\ndocumentation.\n\n\nConfiguring from Data Files\n---------------------------\n\nIt is also possible to load configuration from a file in a format of\nyour choice using :meth:`~flask.Config.from_file`. For example to load\nfrom a TOML file:\n\n.. code-block:: python\n\n import toml\n app.config.from_file(\"config.toml\", load=toml.load)\n\nOr from a JSON file:\n\n.. code-block:: python\n\n import json\n app.config.from_file(\"config.json\", load=json.load)\n\n\nConfiguring from Environment Variables\n--------------------------------------\n\nIn addition to pointing to configuration files using environment variables, you\nmay find it useful (or necessary) to control your configuration values directly\nfrom the environment.\n\nEnvironment variables can be set in the shell before starting the server:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export SECRET_KEY=\"5f352379324c22463451387a0aec5d2f\"\n $ export MAIL_ENABLED=false\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set SECRET_KEY=\"5f352379324c22463451387a0aec5d2f\"\n > set MAIL_ENABLED=false\n > flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:SECRET_KEY = \"5f352379324c22463451387a0aec5d2f\"\n > $env:MAIL_ENABLED = \"false\"\n > flask run\n * Running on http://127.0.0.1:5000/\n\nWhile this approach is straightforward to use, it is important to remember that\nenvironment variables are strings -- they are not automatically deserialized\ninto Python types.\n\nHere is an example of a configuration file that uses environment variables::\n\n import os\n\n _mail_enabled = os.environ.get(\"MAIL_ENABLED\", default=\"true\")\n MAIL_ENABLED = _mail_enabled.lower() in {\"1\", \"t\", \"true\"}\n\n SECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\n if not SECRET_KEY:\n raise ValueError(\"No SECRET_KEY set for Flask application\")\n\n\nNotice that any value besides an empty string will be interpreted as a boolean\n``True`` value in Python, which requires care if an environment explicitly sets\nvalues intended to be ``False``.\n\nMake sure to load the configuration very early on, so that extensions have the\nability to access the configuration when starting up. There are other methods\non the config object as well to load from individual files. For a complete\nreference, read the :class:`~flask.Config` class documentation.\n\n\nConfiguration Best Practices\n----------------------------\n\nThe downside with the approach mentioned earlier is that it makes testing\na little harder. There is no single 100% solution for this problem in\ngeneral, but there are a couple of things you can keep in mind to improve\nthat experience:\n\n1. Create your application in a function and register blueprints on it.\n That way you can create multiple instances of your application with\n different configurations attached which makes unit testing a lot\n easier. You can use this to pass in configuration as needed.\n\n2. Do not write code that needs the configuration at import time. If you\n limit yourself to request-only accesses to the configuration you can\n reconfigure the object later on as needed.\n\n.. _config-dev-prod:\n\nDevelopment / Production\n------------------------\n\nMost applications need more than one configuration. There should be at\nleast separate configurations for the production server and the one used\nduring development. The easiest way to handle this is to use a default\nconfiguration that is always loaded and part of the version control, and a\nseparate configuration that overrides the values as necessary as mentioned\nin the example above::\n\n app = Flask(__name__)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\nThen you just have to add a separate :file:`config.py` file and export\n``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However\nthere are alternative ways as well. For example you could use imports or\nsubclassing.\n\nWhat is very popular in the Django world is to make the import explicit in\nthe config file by adding ``from yourapplication.default_settings\nimport *`` to the top of the file and then overriding the changes by hand.\nYou could also inspect an environment variable like\n``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc\nand import different hard-coded files based on that.\n\nAn interesting pattern is also to use classes and inheritance for\nconfiguration::\n\n class Config(object):\n TESTING = False\n\n class ProductionConfig(Config):\n DATABASE_URI = 'mysql://user@localhost/foo'\n\n class DevelopmentConfig(Config):\n DATABASE_URI = \"sqlite:////tmp/foo.db\"\n\n class TestingConfig(Config):\n DATABASE_URI = 'sqlite:///:memory:'\n TESTING = True\n\nTo enable such a config you just have to call into\n:meth:`~flask.Config.from_object`::\n\n app.config.from_object('configmodule.ProductionConfig')\n\nNote that :meth:`~flask.Config.from_object` does not instantiate the class\nobject. If you need to instantiate the class, such as to access a property,\nthen you must do so before calling :meth:`~flask.Config.from_object`::\n\n from configmodule import ProductionConfig\n app.config.from_object(ProductionConfig())\n\n # Alternatively, import via string:\n from werkzeug.utils import import_string\n cfg = import_string('configmodule.ProductionConfig')()\n app.config.from_object(cfg)\n\nInstantiating the configuration object allows you to use ``@property`` in\nyour configuration classes::\n\n class Config(object):\n \"\"\"Base config, uses staging database server.\"\"\"\n TESTING = False\n DB_SERVER = '192.168.1.56'\n\n @property\n def DATABASE_URI(self): # Note: all caps\n return f\"mysql://user@{self.DB_SERVER}/foo\"\n\n class ProductionConfig(Config):\n \"\"\"Uses production database server.\"\"\"\n DB_SERVER = '192.168.19.32'\n\n class DevelopmentConfig(Config):\n DB_SERVER = 'localhost'\n\n class TestingConfig(Config):\n DB_SERVER = 'localhost'\n DATABASE_URI = 'sqlite:///:memory:'\n\nThere are many different ways and it's up to you how you want to manage\nyour configuration files. However here a list of good recommendations:\n\n- Keep a default configuration in version control. Either populate the\n config with this default configuration or import it in your own\n configuration files before overriding values.\n- Use an environment variable to switch between the configurations.\n This can be done from outside the Python interpreter and makes\n development and deployment much easier because you can quickly and\n easily switch between different configs without having to touch the\n code at all. If you are working often on different projects you can\n even create your own script for sourcing that activates a virtualenv\n and exports the development configuration for you.\n- Use a tool like `fabric`_ in production to push code and\n configurations separately to the production server(s). For some\n details about how to do that, head over to the\n :doc:`/patterns/fabric` pattern.\n\n.. _fabric: https://www.fabfile.org/\n\n\n.. _instance-folders:\n\nInstance Folders\n----------------\n\n.. versionadded:: 0.8\n\nFlask 0.8 introduces instance folders. Flask for a long time made it\npossible to refer to paths relative to the application's folder directly\n(via :attr:`Flask.root_path`). This was also how many developers loaded\nconfigurations stored next to the application. Unfortunately however this\nonly works well if applications are not packages in which case the root\npath refers to the contents of the package.\n\nWith Flask 0.8 a new attribute was introduced:\n:attr:`Flask.instance_path`. It refers to a new concept called the\n“instance folder”. The instance folder is designed to not be under\nversion control and be deployment specific. It's the perfect place to\ndrop things that either change at runtime or configuration files.\n\nYou can either explicitly provide the path of the instance folder when\ncreating the Flask application or you can let Flask autodetect the\ninstance folder. For explicit configuration use the `instance_path`\nparameter::\n\n app = Flask(__name__, instance_path='/path/to/instance/folder')\n\nPlease keep in mind that this path *must* be absolute when provided.\n\nIf the `instance_path` parameter is not provided the following default\nlocations are used:\n\n- Uninstalled module::\n\n /myapp.py\n /instance\n\n- Uninstalled package::\n\n /myapp\n /__init__.py\n /instance\n\n- Installed module or package::\n\n $PREFIX/lib/pythonX.Y/site-packages/myapp\n $PREFIX/var/myapp-instance\n\n ``$PREFIX`` is the prefix of your Python installation. This can be\n ``/usr`` or the path to your virtualenv. You can print the value of\n ``sys.prefix`` to see what the prefix is set to.\n\nSince the config object provided loading of configuration files from\nrelative filenames we made it possible to change the loading via filenames\nto be relative to the instance path if wanted. The behavior of relative\npaths in config files can be flipped between “relative to the application\nroot” (the default) to “relative to instance folder” via the\n`instance_relative_config` switch to the application constructor::\n\n app = Flask(__name__, instance_relative_config=True)\n\nHere is a full example of how to configure Flask to preload the config\nfrom a module and then override the config from a file in the instance\nfolder if it exists::\n\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_pyfile('application.cfg', silent=True)\n\nThe path to the instance folder can be found via the\n:attr:`Flask.instance_path`. Flask also provides a shortcut to open a\nfile from the instance folder with :meth:`Flask.open_instance_resource`.\n\nExample usage for both::\n\n filename = os.path.join(app.instance_path, 'application.cfg')\n with open(filename) as f:\n config = f.read()\n\n # or via open_instance_resource:\n with app.open_instance_resource('application.cfg') as f:\n config = f.read()\n"},{"id":808,"name":"urlprocessors.rst","nodeType":"TextFile","path":"docs/patterns","text":"Using URL Processors\n====================\n\n.. versionadded:: 0.7\n\nFlask 0.7 introduces the concept of URL processors. The idea is that you\nmight have a bunch of resources with common parts in the URL that you\ndon't always explicitly want to provide. For instance you might have a\nbunch of URLs that have the language code in it but you don't want to have\nto handle it in every single function yourself.\n\nURL processors are especially helpful when combined with blueprints. We\nwill handle both application specific URL processors here as well as\nblueprint specifics.\n\nInternationalized Application URLs\n----------------------------------\n\nConsider an application like this::\n\n from flask import Flask, g\n\n app = Flask(__name__)\n\n @app.route('//')\n def index(lang_code):\n g.lang_code = lang_code\n ...\n\n @app.route('//about')\n def about(lang_code):\n g.lang_code = lang_code\n ...\n\nThis is an awful lot of repetition as you have to handle the language code\nsetting on the :data:`~flask.g` object yourself in every single function.\nSure, a decorator could be used to simplify this, but if you want to\ngenerate URLs from one function to another you would have to still provide\nthe language code explicitly which can be annoying.\n\nFor the latter, this is where :func:`~flask.Flask.url_defaults` functions\ncome in. They can automatically inject values into a call to\n:func:`~flask.url_for`. The code below checks if the\nlanguage code is not yet in the dictionary of URL values and if the\nendpoint wants a value named ``'lang_code'``::\n\n @app.url_defaults\n def add_language_code(endpoint, values):\n if 'lang_code' in values or not g.lang_code:\n return\n if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):\n values['lang_code'] = g.lang_code\n\nThe method :meth:`~werkzeug.routing.Map.is_endpoint_expecting` of the URL\nmap can be used to figure out if it would make sense to provide a language\ncode for the given endpoint.\n\nThe reverse of that function are\n:meth:`~flask.Flask.url_value_preprocessor`\\s. They are executed right\nafter the request was matched and can execute code based on the URL\nvalues. The idea is that they pull information out of the values\ndictionary and put it somewhere else::\n\n @app.url_value_preprocessor\n def pull_lang_code(endpoint, values):\n g.lang_code = values.pop('lang_code', None)\n\nThat way you no longer have to do the `lang_code` assignment to\n:data:`~flask.g` in every function. You can further improve that by\nwriting your own decorator that prefixes URLs with the language code, but\nthe more beautiful solution is using a blueprint. Once the\n``'lang_code'`` is popped from the values dictionary and it will no longer\nbe forwarded to the view function reducing the code to this::\n\n from flask import Flask, g\n\n app = Flask(__name__)\n\n @app.url_defaults\n def add_language_code(endpoint, values):\n if 'lang_code' in values or not g.lang_code:\n return\n if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):\n values['lang_code'] = g.lang_code\n\n @app.url_value_preprocessor\n def pull_lang_code(endpoint, values):\n g.lang_code = values.pop('lang_code', None)\n\n @app.route('//')\n def index():\n ...\n\n @app.route('//about')\n def about():\n ...\n\nInternationalized Blueprint URLs\n--------------------------------\n\nBecause blueprints can automatically prefix all URLs with a common string\nit's easy to automatically do that for every function. Furthermore\nblueprints can have per-blueprint URL processors which removes a whole lot\nof logic from the :meth:`~flask.Flask.url_defaults` function because it no\nlonger has to check if the URL is really interested in a ``'lang_code'``\nparameter::\n\n from flask import Blueprint, g\n\n bp = Blueprint('frontend', __name__, url_prefix='/')\n\n @bp.url_defaults\n def add_language_code(endpoint, values):\n values.setdefault('lang_code', g.lang_code)\n\n @bp.url_value_preprocessor\n def pull_lang_code(endpoint, values):\n g.lang_code = values.pop('lang_code')\n\n @bp.route('/')\n def index():\n ...\n\n @bp.route('/about')\n def about():\n ...\n"},{"fileName":"scaffold.py","filePath":"src/flask","id":809,"nodeType":"File","text":"import importlib.util\nimport os\nimport pkgutil\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\nfrom json import JSONDecoder\nfrom json import JSONEncoder\n\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\n\nfrom .cli import AppGroup\nfrom .globals import current_app\nfrom .helpers import get_root_path\nfrom .helpers import locked_cached_property\nfrom .helpers import send_from_directory\nfrom .templating import _default_template_ctx_processor\nfrom .typing import AfterRequestCallable\nfrom .typing import AppOrBlueprintKey\nfrom .typing import BeforeRequestCallable\nfrom .typing import ErrorHandlerCallable\nfrom .typing import TeardownCallable\nfrom .typing import TemplateContextProcessorCallable\nfrom .typing import URLDefaultCallable\nfrom .typing import URLValuePreprocessorCallable\n\nif t.TYPE_CHECKING:\n from .wrappers import Response\n\n# a singleton sentinel value for parameter defaults\n_sentinel = object()\n\n\ndef setupmethod(f: t.Callable) -> t.Callable:\n \"\"\"Wraps a method so that it performs a check in debug mode if the\n first request was already handled.\n \"\"\"\n\n def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if self._is_setup_finished():\n raise AssertionError(\n \"A setup function was called after the first request \"\n \"was handled. This usually indicates a bug in the\"\n \" application where a module was not imported and\"\n \" decorators or other functionality was called too\"\n \" late.\\nTo fix this make sure to import all your view\"\n \" modules, database models, and everything related at a\"\n \" central place before the application starts serving\"\n \" requests.\"\n )\n return f(self, *args, **kwargs)\n\n return update_wrapper(wrapper_func, f)\n\n\nclass Scaffold:\n \"\"\"Common behavior shared between :class:`~flask.Flask` and\n :class:`~flask.blueprints.Blueprint`.\n\n :param import_name: The import name of the module where this object\n is defined. Usually :attr:`__name__` should be used.\n :param static_folder: Path to a folder of static files to serve.\n If this is set, a static route will be added.\n :param static_url_path: URL prefix for the static route.\n :param template_folder: Path to a folder containing template files.\n for rendering. If this is set, a Jinja loader will be added.\n :param root_path: The path that static, template, and resource files\n are relative to. Typically not set, it is discovered based on\n the ``import_name``.\n\n .. versionadded:: 2.0\n \"\"\"\n\n name: str\n _static_folder: t.Optional[str] = None\n _static_url_path: t.Optional[str] = None\n\n #: JSON encoder class used by :func:`flask.json.dumps`. If a\n #: blueprint sets this, it will be used instead of the app's value.\n json_encoder: t.Optional[t.Type[JSONEncoder]] = None\n\n #: JSON decoder class used by :func:`flask.json.loads`. If a\n #: blueprint sets this, it will be used instead of the app's value.\n json_decoder: t.Optional[t.Type[JSONDecoder]] = None\n\n def __init__(\n self,\n import_name: str,\n static_folder: t.Optional[str] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[str] = None,\n root_path: t.Optional[str] = None,\n ):\n #: The name of the package or module that this object belongs\n #: to. Do not change this once it is set by the constructor.\n self.import_name = import_name\n\n self.static_folder = static_folder\n self.static_url_path = static_url_path\n\n #: The path to the templates folder, relative to\n #: :attr:`root_path`, to add to the template loader. ``None`` if\n #: templates should not be added.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Absolute path to the package on the filesystem. Used to look\n #: up resources contained in the package.\n self.root_path = root_path\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n #: A dictionary mapping endpoint names to view functions.\n #:\n #: To register a view function, use the :meth:`route` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.view_functions: t.Dict[str, t.Callable] = {}\n\n #: A data structure of registered error handlers, in the format\n #: ``{scope: {code: {class: handler}}}```. The ``scope`` key is\n #: the name of a blueprint the handlers are active for, or\n #: ``None`` for all requests. The ``code`` key is the HTTP\n #: status code for ``HTTPException``, or ``None`` for\n #: other exceptions. The innermost dictionary maps exception\n #: classes to handler functions.\n #:\n #: To register an error handler, use the :meth:`errorhandler`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.error_handler_spec: t.Dict[\n AppOrBlueprintKey,\n t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],\n ] = defaultdict(lambda: defaultdict(dict))\n\n #: A data structure of functions to call at the beginning of\n #: each request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`before_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.before_request_funcs: t.Dict[\n AppOrBlueprintKey, t.List[BeforeRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`after_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.after_request_funcs: t.Dict[\n AppOrBlueprintKey, t.List[AfterRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request even if an exception is raised, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`teardown_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.teardown_request_funcs: t.Dict[\n AppOrBlueprintKey, t.List[TeardownCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call to pass extra context\n #: values when rendering templates, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`context_processor`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.template_context_processors: t.Dict[\n AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]\n ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n #: A data structure of functions to call to modify the keyword\n #: arguments passed to the view function, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the\n #: :meth:`url_value_preprocessor` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_value_preprocessors: t.Dict[\n AppOrBlueprintKey,\n t.List[URLValuePreprocessorCallable],\n ] = defaultdict(list)\n\n #: A data structure of functions to call to modify the keyword\n #: arguments when generating URLs, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`url_defaults`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_default_functions: t.Dict[\n AppOrBlueprintKey, t.List[URLDefaultCallable]\n ] = defaultdict(list)\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} {self.name!r}>\"\n\n def _is_setup_finished(self) -> bool:\n raise NotImplementedError\n\n @property\n def static_folder(self) -> t.Optional[str]:\n \"\"\"The absolute path to the configured static folder. ``None``\n if no static folder is set.\n \"\"\"\n if self._static_folder is not None:\n return os.path.join(self.root_path, self._static_folder)\n else:\n return None\n\n @static_folder.setter\n def static_folder(self, value: t.Optional[str]) -> None:\n if value is not None:\n value = os.fspath(value).rstrip(r\"\\/\")\n\n self._static_folder = value\n\n @property\n def has_static_folder(self) -> bool:\n \"\"\"``True`` if :attr:`static_folder` is set.\n\n .. versionadded:: 0.5\n \"\"\"\n return self.static_folder is not None\n\n @property\n def static_url_path(self) -> t.Optional[str]:\n \"\"\"The URL prefix that the static route will be accessible from.\n\n If it was not configured during init, it is derived from\n :attr:`static_folder`.\n \"\"\"\n if self._static_url_path is not None:\n return self._static_url_path\n\n if self.static_folder is not None:\n basename = os.path.basename(self.static_folder)\n return f\"/{basename}\".rstrip(\"/\")\n\n return None\n\n @static_url_path.setter\n def static_url_path(self, value: t.Optional[str]) -> None:\n if value is not None:\n value = value.rstrip(\"/\")\n\n self._static_url_path = value\n\n def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:\n \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n value for a given file path if it wasn't passed.\n\n By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n the configuration of :data:`~flask.current_app`. This defaults\n to ``None``, which tells the browser to use conditional requests\n instead of a timed cache, which is usually preferable.\n\n .. versionchanged:: 2.0\n The default configuration is ``None`` instead of 12 hours.\n\n .. versionadded:: 0.9\n \"\"\"\n value = current_app.send_file_max_age_default\n\n if value is None:\n return None\n\n return int(value.total_seconds())\n\n def send_static_file(self, filename: str) -> \"Response\":\n \"\"\"The view function used to serve files from\n :attr:`static_folder`. A route is automatically registered for\n this view at :attr:`static_url_path` if :attr:`static_folder` is\n set.\n\n .. versionadded:: 0.5\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n # send_file only knows to call get_send_file_max_age on the app,\n # call it here so it works for blueprints too.\n max_age = self.get_send_file_max_age(filename)\n return send_from_directory(\n t.cast(str, self.static_folder), filename, max_age=max_age\n )\n\n @locked_cached_property\n def jinja_loader(self) -> t.Optional[FileSystemLoader]:\n \"\"\"The Jinja loader for this object's templates. By default this\n is a class :class:`jinja2.loaders.FileSystemLoader` to\n :attr:`template_folder` if it is set.\n\n .. versionadded:: 0.5\n \"\"\"\n if self.template_folder is not None:\n return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n else:\n return None\n\n def open_resource(self, resource: str, mode: str = \"rb\") -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to :attr:`root_path` for\n reading.\n\n For example, if the file ``schema.sql`` is next to the file\n ``app.py`` where the ``Flask`` app is defined, it can be opened\n with:\n\n .. code-block:: python\n\n with app.open_resource(\"schema.sql\") as f:\n conn.executescript(f.read())\n\n :param resource: Path to the resource relative to\n :attr:`root_path`.\n :param mode: Open the file in this mode. Only reading is\n supported, valid values are \"r\" (or \"rt\") and \"rb\".\n \"\"\"\n if mode not in {\"r\", \"rt\", \"rb\"}:\n raise ValueError(\"Resources can only be opened for reading.\")\n\n return open(os.path.join(self.root_path, resource), mode)\n\n def _method_route(self, method: str, rule: str, options: dict) -> t.Callable:\n if \"methods\" in options:\n raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n return self.route(rule, methods=[method], **options)\n\n def get(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"GET\", rule, options)\n\n def post(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"POST\", rule, options)\n\n def put(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PUT\", rule, options)\n\n def delete(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"DELETE\", rule, options)\n\n def patch(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PATCH\", rule, options)\n\n def route(self, rule: str, **options: t.Any) -> t.Callable:\n \"\"\"Decorate a view function to register it with the given URL\n rule and options. Calls :meth:`add_url_rule`, which has more\n details about the implementation.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n ``OPTIONS`` are added automatically.\n\n :param rule: The URL rule string.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n\n def decorator(f: t.Callable) -> t.Callable:\n endpoint = options.pop(\"endpoint\", None)\n self.add_url_rule(rule, endpoint, f, **options)\n return f\n\n return decorator\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> t.Callable:\n \"\"\"Register a rule for routing incoming requests and building\n URLs. The :meth:`route` decorator is a shortcut to call this\n with the ``view_func`` argument. These are equivalent:\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n ...\n\n .. code-block:: python\n\n def index():\n ...\n\n app.add_url_rule(\"/\", view_func=index)\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed. An error\n will be raised if a function has already been registered for the\n endpoint.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n always added automatically, and ``OPTIONS`` is added\n automatically by default.\n\n ``view_func`` does not necessarily need to be passed, but if the\n rule should participate in routing an endpoint name must be\n associated with a view function at some point with the\n :meth:`endpoint` decorator.\n\n .. code-block:: python\n\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n @app.endpoint(\"index\")\n def index():\n ...\n\n If ``view_func`` has a ``required_methods`` attribute, those\n methods are added to the passed and automatic methods. If it\n has a ``provide_automatic_methods`` attribute, it is used as the\n default if the parameter is not passed.\n\n :param rule: The URL rule string.\n :param endpoint: The endpoint name to associate with the rule\n and view function. Used when routing and building URLs.\n Defaults to ``view_func.__name__``.\n :param view_func: The view function to associate with the\n endpoint name.\n :param provide_automatic_options: Add the ``OPTIONS`` method and\n respond to ``OPTIONS`` requests automatically.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n raise NotImplementedError\n\n def endpoint(self, endpoint: str) -> t.Callable:\n \"\"\"Decorate a view function to register it for the given\n endpoint. Used if a rule is added without a ``view_func`` with\n :meth:`add_url_rule`.\n\n .. code-block:: python\n\n app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n @app.endpoint(\"example\")\n def example():\n ...\n\n :param endpoint: The endpoint name to associate with the view\n function.\n \"\"\"\n\n def decorator(f):\n self.view_functions[endpoint] = f\n return f\n\n return decorator\n\n @setupmethod\n def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:\n \"\"\"Register a function to run before each request.\n\n For example, this can be used to open a database connection, or\n to load the logged in user from the session.\n\n .. code-block:: python\n\n @app.before_request\n def load_user():\n if \"user_id\" in session:\n g.user = db.session.get(session[\"user_id\"])\n\n The function will be called without any arguments. If it returns\n a non-``None`` value, the value is handled as if it was the\n return value from the view, and further request handling is\n stopped.\n \"\"\"\n self.before_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:\n \"\"\"Register a function to run after each request to this object.\n\n The function is called with the response object, and must return\n a response object. This allows the functions to modify or\n replace the response before it is sent.\n\n If a function raises an exception, any remaining\n ``after_request`` functions will not be called. Therefore, this\n should not be used for actions that must execute, such as to\n close resources. Use :meth:`teardown_request` for that.\n \"\"\"\n self.after_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def teardown_request(self, f: TeardownCallable) -> TeardownCallable:\n \"\"\"Register a function to be run at the end of each request,\n regardless of whether there was an exception or not. These functions\n are executed when the request context is popped, even if not an\n actual request was performed.\n\n Example::\n\n ctx = app.test_request_context()\n ctx.push()\n ...\n ctx.pop()\n\n When ``ctx.pop()`` is executed in the above example, the teardown\n functions are called just before the request context moves from the\n stack of active contexts. This becomes relevant if you are using\n such constructs in tests.\n\n Teardown functions must avoid raising exceptions, since they . If they\n execute code that might fail they\n will have to surround the execution of these code by try/except\n statements and log occurring errors.\n\n When a teardown function was called because of an exception it will\n be passed an error object.\n\n The return values of teardown functions are ignored.\n\n .. admonition:: Debug Note\n\n In debug mode Flask will not tear down a request on an exception\n immediately. Instead it will keep it alive so that the interactive\n debugger can still access it. This behavior can be controlled\n by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.\n \"\"\"\n self.teardown_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def context_processor(\n self, f: TemplateContextProcessorCallable\n ) -> TemplateContextProcessorCallable:\n \"\"\"Registers a template context processor function.\"\"\"\n self.template_context_processors[None].append(f)\n return f\n\n @setupmethod\n def url_value_preprocessor(\n self, f: URLValuePreprocessorCallable\n ) -> URLValuePreprocessorCallable:\n \"\"\"Register a URL value preprocessor function for all view\n functions in the application. These functions will be called before the\n :meth:`before_request` functions.\n\n The function can modify the values captured from the matched url before\n they are passed to the view. For example, this can be used to pop a\n common language code value and place it in ``g`` rather than pass it to\n every view.\n\n The function is passed the endpoint name and values dict. The return\n value is ignored.\n \"\"\"\n self.url_value_preprocessors[None].append(f)\n return f\n\n @setupmethod\n def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:\n \"\"\"Callback function for URL defaults for all view functions of the\n application. It's called with the endpoint and values and should\n update the values passed in place.\n \"\"\"\n self.url_default_functions[None].append(f)\n return f\n\n @setupmethod\n def errorhandler(\n self, code_or_exception: t.Union[t.Type[Exception], int]\n ) -> t.Callable:\n \"\"\"Register a function to handle errors by code or exception class.\n\n A decorator that is used to register a function given an\n error code. Example::\n\n @app.errorhandler(404)\n def page_not_found(error):\n return 'This page does not exist', 404\n\n You can also register handlers for arbitrary exceptions::\n\n @app.errorhandler(DatabaseError)\n def special_exception_handler(error):\n return 'Database connection failed', 500\n\n .. versionadded:: 0.7\n Use :meth:`register_error_handler` instead of modifying\n :attr:`error_handler_spec` directly, for application wide error\n handlers.\n\n .. versionadded:: 0.7\n One can now additionally also register custom exception types\n that do not necessarily have to be a subclass of the\n :class:`~werkzeug.exceptions.HTTPException` class.\n\n :param code_or_exception: the code as integer for the handler, or\n an arbitrary exception\n \"\"\"\n\n def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:\n self.register_error_handler(code_or_exception, f)\n return f\n\n return decorator\n\n @setupmethod\n def register_error_handler(\n self,\n code_or_exception: t.Union[t.Type[Exception], int],\n f: ErrorHandlerCallable,\n ) -> None:\n \"\"\"Alternative error attach function to the :meth:`errorhandler`\n decorator that is more straightforward to use for non decorator\n usage.\n\n .. versionadded:: 0.7\n \"\"\"\n if isinstance(code_or_exception, HTTPException): # old broken behavior\n raise ValueError(\n \"Tried to register a handler for an exception instance\"\n f\" {code_or_exception!r}. Handlers can only be\"\n \" registered for exception classes or HTTP error codes.\"\n )\n\n try:\n exc_class, code = self._get_exc_class_and_code(code_or_exception)\n except KeyError:\n raise KeyError(\n f\"'{code_or_exception}' is not a recognized HTTP error\"\n \" code. Use a subclass of HTTPException with that code\"\n \" instead.\"\n )\n\n self.error_handler_spec[None][code][exc_class] = f\n\n @staticmethod\n def _get_exc_class_and_code(\n exc_class_or_code: t.Union[t.Type[Exception], int]\n ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:\n \"\"\"Get the exception class being handled. For HTTP status codes\n or ``HTTPException`` subclasses, return both the exception and\n status code.\n\n :param exc_class_or_code: Any exception class, or an HTTP status\n code as an integer.\n \"\"\"\n exc_class: t.Type[Exception]\n if isinstance(exc_class_or_code, int):\n exc_class = default_exceptions[exc_class_or_code]\n else:\n exc_class = exc_class_or_code\n\n assert issubclass(\n exc_class, Exception\n ), \"Custom exceptions must be subclasses of Exception.\"\n\n if issubclass(exc_class, HTTPException):\n return exc_class, exc_class.code\n else:\n return exc_class, None\n\n\ndef _endpoint_from_view_func(view_func: t.Callable) -> str:\n \"\"\"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n \"\"\"\n assert view_func is not None, \"expected view func if endpoint is not provided.\"\n return view_func.__name__\n\n\ndef _matching_loader_thinks_module_is_package(loader, mod_name):\n \"\"\"Attempt to figure out if the given name is a package or a module.\n\n :param: loader: The loader that handled the name.\n :param mod_name: The name of the package or module.\n \"\"\"\n # Use loader.is_package if it's available.\n if hasattr(loader, \"is_package\"):\n return loader.is_package(mod_name)\n\n cls = type(loader)\n\n # NamespaceLoader doesn't implement is_package, but all names it\n # loads must be packages.\n if cls.__module__ == \"_frozen_importlib\" and cls.__name__ == \"NamespaceLoader\":\n return True\n\n # Otherwise we need to fail with an error that explains what went\n # wrong.\n raise AttributeError(\n f\"'{cls.__name__}.is_package()' must be implemented for PEP 302\"\n f\" import hooks.\"\n )\n\n\ndef _find_package_path(root_mod_name):\n \"\"\"Find the path that contains the package or module.\"\"\"\n try:\n spec = importlib.util.find_spec(root_mod_name)\n\n if spec is None:\n raise ValueError(\"not found\")\n # ImportError: the machinery told us it does not exist\n # ValueError:\n # - the module name was invalid\n # - the module name is __main__\n # - *we* raised `ValueError` due to `spec` being `None`\n except (ImportError, ValueError):\n pass # handled below\n else:\n # namespace package\n if spec.origin in {\"namespace\", None}:\n return os.path.dirname(next(iter(spec.submodule_search_locations)))\n # a package (with __init__.py)\n elif spec.submodule_search_locations:\n return os.path.dirname(os.path.dirname(spec.origin))\n # just a normal module\n else:\n return os.path.dirname(spec.origin)\n\n # we were unable to find the `package_path` using PEP 451 loaders\n loader = pkgutil.get_loader(root_mod_name)\n\n if loader is None or root_mod_name == \"__main__\":\n # import name is not found, or interactive/main module\n return os.getcwd()\n\n if hasattr(loader, \"get_filename\"):\n filename = loader.get_filename(root_mod_name)\n elif hasattr(loader, \"archive\"):\n # zipimporter's loader.archive points to the .egg or .zip file.\n filename = loader.archive\n else:\n # At least one loader is missing both get_filename and archive:\n # Google App Engine's HardenedModulesHook, use __file__.\n filename = importlib.import_module(root_mod_name).__file__\n\n package_path = os.path.abspath(os.path.dirname(filename))\n\n # If the imported name is a package, filename is currently pointing\n # to the root of the package, need to get the current directory.\n if _matching_loader_thinks_module_is_package(loader, root_mod_name):\n package_path = os.path.dirname(package_path)\n\n return package_path\n\n\ndef find_package(import_name: str):\n \"\"\"Find the prefix that a package is installed under, and the path\n that it would be imported from.\n\n The prefix is the directory containing the standard directory\n hierarchy (lib, bin, etc.). If the package is not installed to the\n system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),\n ``None`` is returned.\n\n The path is the entry in :attr:`sys.path` that contains the package\n for import. If the package is not installed, it's assumed that the\n package was imported from the current working directory.\n \"\"\"\n root_mod_name, _, _ = import_name.partition(\".\")\n package_path = _find_package_path(root_mod_name)\n py_prefix = os.path.abspath(sys.prefix)\n\n # installed to the system\n if package_path.startswith(py_prefix):\n return py_prefix, package_path\n\n site_parent, site_folder = os.path.split(package_path)\n\n # installed to a virtualenv\n if site_folder.lower() == \"site-packages\":\n parent, folder = os.path.split(site_parent)\n\n # Windows (prefix/lib/site-packages)\n if folder.lower() == \"lib\":\n return parent, package_path\n\n # Unix (prefix/lib/pythonX.Y/site-packages)\n if os.path.basename(parent).lower() == \"lib\":\n return os.path.dirname(parent), package_path\n\n # something else (prefix/site-packages)\n return site_parent, package_path\n\n # not installed\n return None, package_path\n"},{"id":810,"name":"shell.rst","nodeType":"TextFile","path":"docs","text":"Working with the Shell\n======================\n\n.. versionadded:: 0.3\n\nOne of the reasons everybody loves Python is the interactive shell. It\nbasically allows you to execute Python commands in real time and\nimmediately get results back. Flask itself does not come with an\ninteractive shell, because it does not require any specific setup upfront,\njust import your application and start playing around.\n\nThere are however some handy helpers to make playing around in the shell a\nmore pleasant experience. The main issue with interactive console\nsessions is that you're not triggering a request like a browser does which\nmeans that :data:`~flask.g`, :data:`~flask.request` and others are not\navailable. But the code you want to test might depend on them, so what\ncan you do?\n\nThis is where some helper functions come in handy. Keep in mind however\nthat these functions are not only there for interactive shell usage, but\nalso for unit testing and other situations that require a faked request\ncontext.\n\nGenerally it's recommended that you read the :doc:`reqcontext`\nchapter of the documentation first.\n\nCommand Line Interface\n----------------------\n\nStarting with Flask 0.11 the recommended way to work with the shell is the\n``flask shell`` command which does a lot of this automatically for you.\nFor instance the shell is automatically initialized with a loaded\napplication context.\n\nFor more information see :doc:`/cli`.\n\nCreating a Request Context\n--------------------------\n\nThe easiest way to create a proper request context from the shell is by\nusing the :attr:`~flask.Flask.test_request_context` method which creates\nus a :class:`~flask.ctx.RequestContext`:\n\n>>> ctx = app.test_request_context()\n\nNormally you would use the ``with`` statement to make this request object\nactive, but in the shell it's easier to use the\n:meth:`~flask.ctx.RequestContext.push` and\n:meth:`~flask.ctx.RequestContext.pop` methods by hand:\n\n>>> ctx.push()\n\nFrom that point onwards you can work with the request object until you\ncall `pop`:\n\n>>> ctx.pop()\n\nFiring Before/After Request\n---------------------------\n\nBy just creating a request context, you still don't have run the code that\nis normally run before a request. This might result in your database\nbeing unavailable if you are connecting to the database in a\nbefore-request callback or the current user not being stored on the\n:data:`~flask.g` object etc.\n\nThis however can easily be done yourself. Just call\n:meth:`~flask.Flask.preprocess_request`:\n\n>>> ctx = app.test_request_context()\n>>> ctx.push()\n>>> app.preprocess_request()\n\nKeep in mind that the :meth:`~flask.Flask.preprocess_request` function\nmight return a response object, in that case just ignore it.\n\nTo shutdown a request, you need to trick a bit before the after request\nfunctions (triggered by :meth:`~flask.Flask.process_response`) operate on\na response object:\n\n>>> app.process_response(app.response_class())\n\n>>> ctx.pop()\n\nThe functions registered as :meth:`~flask.Flask.teardown_request` are\nautomatically called when the context is popped. So this is the perfect\nplace to automatically tear down resources that were needed by the request\ncontext (such as database connections).\n\n\nFurther Improving the Shell Experience\n--------------------------------------\n\nIf you like the idea of experimenting in a shell, create yourself a module\nwith stuff you want to star import into your interactive session. There\nyou could also define some more helper methods for common things such as\ninitializing the database, dropping tables etc.\n\nJust put them into a module (like `shelltools`) and import from there:\n\n>>> from shelltools import *\n"},{"className":"AppGroup","col":0,"comment":"This works similar to a regular click :class:`~click.Group` but it\n changes the behavior of the :meth:`command` decorator so that it\n automatically wraps the functions in :func:`with_appcontext`.\n\n Not to be confused with :class:`FlaskGroup`.\n ","endLoc":473,"id":811,"nodeType":"Class","startLoc":445,"text":"class AppGroup(click.Group):\n \"\"\"This works similar to a regular click :class:`~click.Group` but it\n changes the behavior of the :meth:`command` decorator so that it\n automatically wraps the functions in :func:`with_appcontext`.\n\n Not to be confused with :class:`FlaskGroup`.\n \"\"\"\n\n def command(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f):\n if wrap_for_ctx:\n f = with_appcontext(f)\n return click.Group.command(self, *args, **kwargs)(f)\n\n return decorator\n\n def group(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n \"\"\"\n kwargs.setdefault(\"cls\", AppGroup)\n return click.Group.group(self, *args, **kwargs)"},{"col":4,"comment":"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n ","endLoc":465,"header":"def command(self, *args, **kwargs)","id":812,"name":"command","nodeType":"Function","startLoc":453,"text":"def command(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f):\n if wrap_for_ctx:\n f = with_appcontext(f)\n return click.Group.command(self, *args, **kwargs)(f)\n\n return decorator"},{"col":0,"comment":"Wraps a callback so that it's guaranteed to be executed with the\n script's application context. If callbacks are registered directly\n to the ``app.cli`` object then they are wrapped with this function\n by default unless it's disabled.\n ","endLoc":442,"header":"def with_appcontext(f)","id":813,"name":"with_appcontext","nodeType":"Function","startLoc":430,"text":"def with_appcontext(f):\n \"\"\"Wraps a callback so that it's guaranteed to be executed with the\n script's application context. If callbacks are registered directly\n to the ``app.cli`` object then they are wrapped with this function\n by default unless it's disabled.\n \"\"\"\n\n @click.pass_context\n def decorator(__ctx, *args, **kwargs):\n with __ctx.ensure_object(ScriptInfo).load_app().app_context():\n return __ctx.invoke(f, *args, **kwargs)\n\n return update_wrapper(decorator, f)"},{"col":4,"comment":"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n ","endLoc":473,"header":"def group(self, *args, **kwargs)","id":814,"name":"group","nodeType":"Function","startLoc":467,"text":"def group(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n \"\"\"\n kwargs.setdefault(\"cls\", AppGroup)\n return click.Group.group(self, *args, **kwargs)"},{"id":815,"name":"server.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nDevelopment Server\n==================\n\nFlask provides a ``run`` command to run the application with a\ndevelopment server. In development mode, this server provides an\ninteractive debugger and will reload when code is changed.\n\n.. warning::\n\n Do not use the development server when deploying to production. It\n is intended for use only during local development. It is not\n designed to be particularly efficient, stable, or secure.\n\n See :doc:`/deploying/index` for deployment options.\n\nCommand Line\n------------\n\nThe ``flask run`` command line script is the recommended way to run the\ndevelopment server. It requires setting the ``FLASK_APP`` environment\nvariable to point to your application, and ``FLASK_ENV=development`` to\nfully enable development mode.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=hello\n $ export FLASK_ENV=development\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=hello\n > set FLASK_ENV=development\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"hello\"\n > $env:FLASK_ENV = \"development\"\n > flask run\n\nThis enables the development environment, including the interactive\ndebugger and reloader, and then starts the server on\nhttp://localhost:5000/. Use ``flask run --help`` to see the available\noptions, and :doc:`/cli` for detailed instructions about configuring\nand using the CLI.\n\n.. note::\n\n Prior to Flask 1.0 the ``FLASK_ENV`` environment variable was not\n supported and you needed to enable debug mode by exporting\n ``FLASK_DEBUG=1``. This can still be used to control debug mode, but\n you should prefer setting the development environment as shown\n above.\n\n\nLazy or Eager Loading\n~~~~~~~~~~~~~~~~~~~~~\n\nWhen using the ``flask run`` command with the reloader, the server will\ncontinue to run even if you introduce syntax errors or other\ninitialization errors into the code. Accessing the site will show the\ninteractive debugger for the error, rather than crashing the server.\nThis feature is called \"lazy loading\".\n\nIf a syntax error is already present when calling ``flask run``, it will\nfail immediately and show the traceback rather than waiting until the\nsite is accessed. This is intended to make errors more visible initially\nwhile still allowing the server to handle errors on reload.\n\nTo override this behavior and always fail immediately, even on reload,\npass the ``--eager-loading`` option. To always keep the server running,\neven on the initial call, pass ``--lazy-loading``.\n\n\nIn Code\n-------\n\nAs an alternative to the ``flask run`` command, the development server\ncan also be started from Python with the :meth:`Flask.run` method. This\nmethod takes arguments similar to the CLI options to control the server.\nThe main difference from the CLI command is that the server will crash\nif there are errors when reloading.\n\n``debug=True`` can be passed to enable the debugger and reloader, but\nthe ``FLASK_ENV=development`` environment variable is still required to\nfully enable development mode.\n\nPlace the call in a main block, otherwise it will interfere when trying\nto import and run the application with a production server later.\n\n.. code-block:: python\n\n if __name__ == \"__main__\":\n app.run(debug=True)\n\n.. code-block:: text\n\n $ python hello.py\n"},{"id":816,"name":"update.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/blog","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Edit \"{{ post['title'] }}\"{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n
\n
\n \n
\n{% endblock %}\n"},{"col":0,"comment":"Wraps a method so that it performs a check in debug mode if the\n first request was already handled.\n ","endLoc":56,"header":"def setupmethod(f: t.Callable) -> t.Callable","id":817,"name":"setupmethod","nodeType":"Function","startLoc":37,"text":"def setupmethod(f: t.Callable) -> t.Callable:\n \"\"\"Wraps a method so that it performs a check in debug mode if the\n first request was already handled.\n \"\"\"\n\n def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:\n if self._is_setup_finished():\n raise AssertionError(\n \"A setup function was called after the first request \"\n \"was handled. This usually indicates a bug in the\"\n \" application where a module was not imported and\"\n \" decorators or other functionality was called too\"\n \" late.\\nTo fix this make sure to import all your view\"\n \" modules, database models, and everything related at a\"\n \" central place before the application starts serving\"\n \" requests.\"\n )\n return f(self, *args, **kwargs)\n\n return update_wrapper(wrapper_func, f)"},{"id":818,"name":"packages.rst","nodeType":"TextFile","path":"docs/patterns","text":"Large Applications as Packages\n==============================\n\nImagine a simple flask application structure that looks like this::\n\n /yourapplication\n yourapplication.py\n /static\n style.css\n /templates\n layout.html\n index.html\n login.html\n ...\n\nWhile this is fine for small applications, for larger applications\nit's a good idea to use a package instead of a module.\nThe :doc:`/tutorial/index` is structured to use the package pattern,\nsee the :gh:`example code `.\n\nSimple Packages\n---------------\n\nTo convert that into a larger one, just create a new folder\n:file:`yourapplication` inside the existing one and move everything below it.\nThen rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete\nall ``.pyc`` files first, otherwise things would most likely break)\n\nYou should then end up with something like that::\n\n /yourapplication\n /yourapplication\n __init__.py\n /static\n style.css\n /templates\n layout.html\n index.html\n login.html\n ...\n\nBut how do you run your application now? The naive ``python\nyourapplication/__init__.py`` will not work. Let's just say that Python\ndoes not want modules in packages to be the startup file. But that is not\na big problem, just add a new file called :file:`setup.py` next to the inner\n:file:`yourapplication` folder with the following contents::\n\n from setuptools import setup\n\n setup(\n name='yourapplication',\n packages=['yourapplication'],\n include_package_data=True,\n install_requires=[\n 'flask',\n ],\n )\n\nIn order to run the application you need to export an environment variable\nthat tells Flask where to find the application instance:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=yourapplication\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=yourapplication\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"yourapplication\"\n\nIf you are outside of the project directory make sure to provide the exact\npath to your application directory. Similarly you can turn on the\ndevelopment features like this:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_ENV=development\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_ENV=development\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_ENV = \"development\"\n\nIn order to install and run the application you need to issue the following\ncommands::\n\n $ pip install -e .\n $ flask run\n\nWhat did we gain from this? Now we can restructure the application a bit\ninto multiple modules. The only thing you have to remember is the\nfollowing quick checklist:\n\n1. the `Flask` application object creation has to be in the\n :file:`__init__.py` file. That way each module can import it safely and the\n `__name__` variable will resolve to the correct package.\n2. all the view functions (the ones with a :meth:`~flask.Flask.route`\n decorator on top) have to be imported in the :file:`__init__.py` file.\n Not the object itself, but the module it is in. Import the view module\n **after the application object is created**.\n\nHere's an example :file:`__init__.py`::\n\n from flask import Flask\n app = Flask(__name__)\n\n import yourapplication.views\n\nAnd this is what :file:`views.py` would look like::\n\n from yourapplication import app\n\n @app.route('/')\n def index():\n return 'Hello World!'\n\nYou should then end up with something like that::\n\n /yourapplication\n setup.py\n /yourapplication\n __init__.py\n views.py\n /static\n style.css\n /templates\n layout.html\n index.html\n login.html\n ...\n\n.. admonition:: Circular Imports\n\n Every Python programmer hates them, and yet we just added some:\n circular imports (That's when two modules depend on each other. In this\n case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a\n bad idea in general but here it is actually fine. The reason for this is\n that we are not actually using the views in :file:`__init__.py` and just\n ensuring the module is imported and we are doing that at the bottom of\n the file.\n\n There are still some problems with that approach but if you want to use\n decorators there is no way around that. Check out the\n :doc:`/becomingbig` section for some inspiration how to deal with that.\n\n\nWorking with Blueprints\n-----------------------\n\nIf you have larger applications it's recommended to divide them into\nsmaller groups where each group is implemented with the help of a\nblueprint. For a gentle introduction into this topic refer to the\n:doc:`/blueprints` chapter of the documentation.\n"},{"id":819,"name":"logo-full.svg","nodeType":"TextFile","path":"artwork","text":"\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"id":820,"name":"tox.ini","nodeType":"TextFile","path":"","text":"[tox]\nenvlist =\n py{39,38,37,36,py3}\n py39-click7\n style\n typing\n docs\nskip_missing_interpreters = true\n\n[testenv]\ndeps =\n -r requirements/tests.txt\n\n click7: click<8\n\n examples/tutorial[test]\n examples/javascript[test]\ncommands = pytest -v --tb=short --basetemp={envtmpdir} {posargs:tests examples}\n\n[testenv:style]\ndeps = pre-commit\nskip_install = true\ncommands = pre-commit run --all-files --show-diff-on-failure\n\n[testenv:typing]\ndeps = -r requirements/typing.txt\ncommands = mypy\n\n[testenv:docs]\ndeps = -r requirements/docs.txt\ncommands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html\n"},{"id":821,"name":"logging.rst","nodeType":"TextFile","path":"docs","text":"Logging\n=======\n\nFlask uses standard Python :mod:`logging`. Messages about your Flask\napplication are logged with :meth:`app.logger `,\nwhich takes the same name as :attr:`app.name `. This\nlogger can also be used to log your own messages.\n\n.. code-block:: python\n\n @app.route('/login', methods=['POST'])\n def login():\n user = get_user(request.form['username'])\n\n if user.check_password(request.form['password']):\n login_user(user)\n app.logger.info('%s logged in successfully', user.username)\n return redirect(url_for('index'))\n else:\n app.logger.info('%s failed to log in', user.username)\n abort(401)\n\nIf you don't configure logging, Python's default log level is usually\n'warning'. Nothing below the configured level will be visible.\n\n\nBasic Configuration\n-------------------\n\nWhen you want to configure logging for your project, you should do it as soon\nas possible when the program starts. If :meth:`app.logger `\nis accessed before logging is configured, it will add a default handler. If\npossible, configure logging before creating the application object.\n\nThis example uses :func:`~logging.config.dictConfig` to create a logging\nconfiguration similar to Flask's default, except for all logs::\n\n from logging.config import dictConfig\n\n dictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',\n }},\n 'handlers': {'wsgi': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://flask.logging.wsgi_errors_stream',\n 'formatter': 'default'\n }},\n 'root': {\n 'level': 'INFO',\n 'handlers': ['wsgi']\n }\n })\n\n app = Flask(__name__)\n\n\nDefault Configuration\n`````````````````````\n\nIf you do not configure logging yourself, Flask will add a\n:class:`~logging.StreamHandler` to :meth:`app.logger `\nautomatically. During requests, it will write to the stream specified by the\nWSGI server in ``environ['wsgi.errors']`` (which is usually\n:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.\n\n\nRemoving the Default Handler\n````````````````````````````\n\nIf you configured logging after accessing\n:meth:`app.logger `, and need to remove the default\nhandler, you can import and remove it::\n\n from flask.logging import default_handler\n\n app.logger.removeHandler(default_handler)\n\n\nEmail Errors to Admins\n----------------------\n\nWhen running the application on a remote server for production, you probably\nwon't be looking at the log messages very often. The WSGI server will probably\nsend log messages to a file, and you'll only check that file if a user tells\nyou something went wrong.\n\nTo be proactive about discovering and fixing bugs, you can configure a\n:class:`logging.handlers.SMTPHandler` to send an email when errors and higher\nare logged. ::\n\n import logging\n from logging.handlers import SMTPHandler\n\n mail_handler = SMTPHandler(\n mailhost='127.0.0.1',\n fromaddr='server-error@example.com',\n toaddrs=['admin@example.com'],\n subject='Application Error'\n )\n mail_handler.setLevel(logging.ERROR)\n mail_handler.setFormatter(logging.Formatter(\n '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'\n ))\n\n if not app.debug:\n app.logger.addHandler(mail_handler)\n\nThis requires that you have an SMTP server set up on the same server. See the\nPython docs for more information about configuring the handler.\n\n\nInjecting Request Information\n-----------------------------\n\nSeeing more information about the request, such as the IP address, may help\ndebugging some errors. You can subclass :class:`logging.Formatter` to inject\nyour own fields that can be used in messages. You can change the formatter for\nFlask's default handler, the mail handler defined above, or any other\nhandler. ::\n\n from flask import has_request_context, request\n from flask.logging import default_handler\n\n class RequestFormatter(logging.Formatter):\n def format(self, record):\n if has_request_context():\n record.url = request.url\n record.remote_addr = request.remote_addr\n else:\n record.url = None\n record.remote_addr = None\n\n return super().format(record)\n\n formatter = RequestFormatter(\n '[%(asctime)s] %(remote_addr)s requested %(url)s\\n'\n '%(levelname)s in %(module)s: %(message)s'\n )\n default_handler.setFormatter(formatter)\n mail_handler.setFormatter(formatter)\n\n\nOther Libraries\n---------------\n\nOther libraries may use logging extensively, and you want to see relevant\nmessages from those logs too. The simplest way to do this is to add handlers\nto the root logger instead of only the app logger. ::\n\n from flask.logging import default_handler\n\n root = logging.getLogger()\n root.addHandler(default_handler)\n root.addHandler(mail_handler)\n\nDepending on your project, it may be more useful to configure each logger you\ncare about separately, instead of configuring only the root logger. ::\n\n for logger in (\n app.logger,\n logging.getLogger('sqlalchemy'),\n logging.getLogger('other_package'),\n ):\n logger.addHandler(default_handler)\n logger.addHandler(mail_handler)\n\n\nWerkzeug\n````````\n\nWerkzeug logs basic request/response information to the ``'werkzeug'`` logger.\nIf the root logger has no handlers configured, Werkzeug adds a\n:class:`~logging.StreamHandler` to its logger.\n\n\nFlask Extensions\n````````````````\n\nDepending on the situation, an extension may choose to log to\n:meth:`app.logger ` or its own named logger. Consult each\nextension's documentation for details.\n"},{"id":822,"name":"examples/tutorial/tests","nodeType":"Package"},{"fileName":"conftest.py","filePath":"examples/tutorial/tests","id":823,"nodeType":"File","text":"import os\nimport tempfile\n\nimport pytest\n\nfrom flaskr import create_app\nfrom flaskr.db import get_db\nfrom flaskr.db import init_db\n\n# read in SQL for populating test data\nwith open(os.path.join(os.path.dirname(__file__), \"data.sql\"), \"rb\") as f:\n _data_sql = f.read().decode(\"utf8\")\n\n\n@pytest.fixture\ndef app():\n \"\"\"Create and configure a new app instance for each test.\"\"\"\n # create a temporary file to isolate the database for each test\n db_fd, db_path = tempfile.mkstemp()\n # create the app with common test config\n app = create_app({\"TESTING\": True, \"DATABASE\": db_path})\n\n # create the database and load test data\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n # close and remove the temporary database\n os.close(db_fd)\n os.unlink(db_path)\n\n\n@pytest.fixture\ndef client(app):\n \"\"\"A test client for the app.\"\"\"\n return app.test_client()\n\n\n@pytest.fixture\ndef runner(app):\n \"\"\"A test runner for the app's Click commands.\"\"\"\n return app.test_cli_runner()\n\n\nclass AuthActions:\n def __init__(self, client):\n self._client = client\n\n def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )\n\n def logout(self):\n return self._client.get(\"/auth/logout\")\n\n\n@pytest.fixture\ndef auth(client):\n return AuthActions(client)\n"},{"col":0,"comment":"","endLoc":1,"header":"scaffold.py#","id":824,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .wrappers import Response\n\n_sentinel = object()"},{"className":"AuthActions","col":0,"comment":"null","endLoc":57,"id":825,"nodeType":"Class","startLoc":47,"text":"class AuthActions:\n def __init__(self, client):\n self._client = client\n\n def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )\n\n def logout(self):\n return self._client.get(\"/auth/logout\")"},{"col":4,"comment":"null","endLoc":49,"header":"def __init__(self, client)","id":826,"name":"__init__","nodeType":"Function","startLoc":48,"text":"def __init__(self, client):\n self._client = client"},{"col":4,"comment":"null","endLoc":54,"header":"def login(self, username=\"test\", password=\"test\")","id":827,"name":"login","nodeType":"Function","startLoc":51,"text":"def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )"},{"fileName":"setup.py","filePath":"examples/javascript","id":828,"nodeType":"File","text":"from setuptools import setup\n\nsetup()\n"},{"col":0,"comment":"","endLoc":1,"header":"setup.py#","id":829,"name":"","nodeType":"Function","startLoc":1,"text":"setup()"},{"id":830,"name":"sqlite3.rst","nodeType":"TextFile","path":"docs/patterns","text":"Using SQLite 3 with Flask\n=========================\n\nIn Flask you can easily implement the opening of database connections on\ndemand and closing them when the context dies (usually at the end of the\nrequest).\n\nHere is a simple example of how you can use SQLite 3 with Flask::\n\n import sqlite3\n from flask import g\n\n DATABASE = '/path/to/database.db'\n\n def get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n @app.teardown_appcontext\n def close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\nNow, to use the database, the application must either have an active\napplication context (which is always true if there is a request in flight)\nor create an application context itself. At that point the ``get_db``\nfunction can be used to get the current database connection. Whenever the\ncontext is destroyed the database connection will be terminated.\n\nNote: if you use Flask 0.9 or older you need to use\n``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`\nobject was bound to the request and not application context.\n\nExample::\n\n @app.route('/')\n def index():\n cur = get_db().cursor()\n ...\n\n\n.. note::\n\n Please keep in mind that the teardown request and appcontext functions\n are always executed, even if a before-request handler failed or was\n never executed. Because of this we have to make sure here that the\n database is there before we close it.\n\nConnect on Demand\n-----------------\n\nThe upside of this approach (connecting on first use) is that this will\nonly open the connection if truly necessary. If you want to use this\ncode outside a request context you can use it in a Python shell by opening\nthe application context by hand::\n\n with app.app_context():\n # now you can use get_db()\n\n\nEasy Querying\n-------------\n\nNow in each request handling function you can access `get_db()` to get the\ncurrent open database connection. To simplify working with SQLite, a\nrow factory function is useful. It is executed for every result returned\nfrom the database to convert the result. For instance, in order to get\ndictionaries instead of tuples, this could be inserted into the ``get_db``\nfunction we created above::\n\n def make_dicts(cursor, row):\n return dict((cursor.description[idx][0], value)\n for idx, value in enumerate(row))\n\n db.row_factory = make_dicts\n\nThis will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::\n\n db.row_factory = sqlite3.Row\n\nThis would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::\n\n >>> # You can get values based on the row's name\n >>> r['FirstName']\n John\n >>> # Or, you can get them based on index\n >>> r[1]\n John\n # Row objects are also iterable:\n >>> for value in r:\n ... print(value)\n 1\n John\n Doe\n M\n\nAdditionally, it is a good idea to provide a query function that combines\ngetting the cursor, executing and fetching the results::\n\n def query_db(query, args=(), one=False):\n cur = get_db().execute(query, args)\n rv = cur.fetchall()\n cur.close()\n return (rv[0] if rv else None) if one else rv\n\nThis handy little function, in combination with a row factory, makes\nworking with the database much more pleasant than it is by just using the\nraw cursor and connection objects.\n\nHere is how you can use it::\n\n for user in query_db('select * from users'):\n print user['username'], 'has the id', user['user_id']\n\nOr if you just want a single result::\n\n user = query_db('select * from users where username = ?',\n [the_username], one=True)\n if user is None:\n print 'No such user'\n else:\n print the_username, 'has the id', user['user_id']\n\nTo pass variable parts to the SQL statement, use a question mark in the\nstatement and pass in the arguments as a list. Never directly add them to\nthe SQL statement with string formatting because this makes it possible\nto attack the application using `SQL Injections\n`_.\n\nInitial Schemas\n---------------\n\nRelational databases need schemas, so applications often ship a\n`schema.sql` file that creates the database. It's a good idea to provide\na function that creates the database based on that schema. This function\ncan do that for you::\n\n def init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\nYou can then create such a database from the Python shell:\n\n>>> from yourapplication import init_db\n>>> init_db()\n"},{"id":831,"name":"tests/templates/nested","nodeType":"Package"},{"id":832,"name":"nested.txt","nodeType":"TextFile","path":"tests/templates/nested","text":"I'm nested\n"},{"fileName":"views.py","filePath":"src/flask","id":833,"nodeType":"File","text":"import typing as t\n\nfrom .globals import request\nfrom .typing import ResponseReturnValue\n\n\nhttp_method_funcs = frozenset(\n [\"get\", \"post\", \"head\", \"options\", \"delete\", \"put\", \"trace\", \"patch\"]\n)\n\n\nclass View:\n \"\"\"Alternative way to use view functions. A subclass has to implement\n :meth:`dispatch_request` which is called with the view arguments from\n the URL routing system. If :attr:`methods` is provided the methods\n do not have to be passed to the :meth:`~flask.Flask.add_url_rule`\n method explicitly::\n\n class MyView(View):\n methods = ['GET']\n\n def dispatch_request(self, name):\n return f\"Hello {name}!\"\n\n app.add_url_rule('/hello/', view_func=MyView.as_view('myview'))\n\n When you want to decorate a pluggable view you will have to either do that\n when the view function is created (by wrapping the return value of\n :meth:`as_view`) or you can use the :attr:`decorators` attribute::\n\n class SecretView(View):\n methods = ['GET']\n decorators = [superuser_required]\n\n def dispatch_request(self):\n ...\n\n The decorators stored in the decorators list are applied one after another\n when the view function is created. Note that you can *not* use the class\n based decorators since those would decorate the view class and not the\n generated view function!\n \"\"\"\n\n #: A list of methods this view can handle.\n methods: t.Optional[t.List[str]] = None\n\n #: Setting this disables or force-enables the automatic options handling.\n provide_automatic_options: t.Optional[bool] = None\n\n #: The canonical way to decorate class-based views is to decorate the\n #: return value of as_view(). However since this moves parts of the\n #: logic from the class declaration to the place where it's hooked\n #: into the routing system.\n #:\n #: You can place one or more decorators in this list and whenever the\n #: view function is created the result is automatically decorated.\n #:\n #: .. versionadded:: 0.8\n decorators: t.List[t.Callable] = []\n\n def dispatch_request(self) -> ResponseReturnValue:\n \"\"\"Subclasses have to override this method to implement the\n actual view function code. This method is called with all\n the arguments from the URL rule.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> t.Callable:\n \"\"\"Converts the class into an actual view function that can be used\n with the routing system. Internally this generates a function on the\n fly which will instantiate the :class:`View` on each request and call\n the :meth:`dispatch_request` method on it.\n\n The arguments passed to :meth:`as_view` are forwarded to the\n constructor of the class.\n \"\"\"\n\n def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n self = view.view_class(*class_args, **class_kwargs) # type: ignore\n return self.dispatch_request(*args, **kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view\n\n\nclass MethodViewType(type):\n \"\"\"Metaclass for :class:`MethodView` that determines what methods the view\n defines.\n \"\"\"\n\n def __init__(cls, name, bases, d):\n super().__init__(name, bases, d)\n\n if \"methods\" not in d:\n methods = set()\n\n for base in bases:\n if getattr(base, \"methods\", None):\n methods.update(base.methods)\n\n for key in http_method_funcs:\n if hasattr(cls, key):\n methods.add(key.upper())\n\n # If we have no method at all in there we don't want to add a\n # method list. This is for instance the case for the base class\n # or another subclass of a base method view that does not introduce\n # new methods.\n if methods:\n cls.methods = methods\n\n\nclass MethodView(View, metaclass=MethodViewType):\n \"\"\"A class-based view that dispatches request methods to the corresponding\n class methods. For example, if you implement a ``get`` method, it will be\n used to handle ``GET`` requests. ::\n\n class CounterAPI(MethodView):\n def get(self):\n return session.get('counter', 0)\n\n def post(self):\n session['counter'] = session.get('counter', 0) + 1\n return 'OK'\n\n app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))\n \"\"\"\n\n def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n meth = getattr(self, request.method.lower(), None)\n\n # If the request method is HEAD and we don't have a handler for it\n # retry with GET.\n if meth is None and request.method == \"HEAD\":\n meth = getattr(self, \"get\", None)\n\n assert meth is not None, f\"Unimplemented method {request.method!r}\"\n return meth(*args, **kwargs)\n"},{"col":4,"comment":"null","endLoc":57,"header":"def logout(self)","id":834,"name":"logout","nodeType":"Function","startLoc":56,"text":"def logout(self):\n return self._client.get(\"/auth/logout\")"},{"attributeType":"null","col":8,"comment":"null","endLoc":49,"id":835,"name":"_client","nodeType":"Attribute","startLoc":49,"text":"self._client"},{"col":0,"comment":"Create and configure a new app instance for each test.","endLoc":32,"header":"@pytest.fixture\ndef app()","id":836,"name":"app","nodeType":"Function","startLoc":15,"text":"@pytest.fixture\ndef app():\n \"\"\"Create and configure a new app instance for each test.\"\"\"\n # create a temporary file to isolate the database for each test\n db_fd, db_path = tempfile.mkstemp()\n # create the app with common test config\n app = create_app({\"TESTING\": True, \"DATABASE\": db_path})\n\n # create the database and load test data\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n # close and remove the temporary database\n os.close(db_fd)\n os.unlink(db_path)"},{"col":4,"comment":"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n ","endLoc":424,"header":"def load_app(self)","id":837,"name":"load_app","nodeType":"Function","startLoc":384,"text":"def load_app(self):\n \"\"\"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n \"\"\"\n __traceback_hide__ = True # noqa: F841\n\n if self._loaded_app is not None:\n return self._loaded_app\n\n if self.create_app is not None:\n app = call_factory(self, self.create_app)\n else:\n if self.app_import_path:\n path, name = (\n re.split(r\":(?![\\\\/])\", self.app_import_path, 1) + [None]\n )[:2]\n import_name = prepare_import(path)\n app = locate_app(self, import_name, name)\n else:\n for path in (\"wsgi.py\", \"app.py\"):\n import_name = prepare_import(path)\n app = locate_app(self, import_name, None, raise_if_not_found=False)\n\n if app:\n break\n\n if not app:\n raise NoAppException(\n \"Could not locate a Flask application. You did not provide \"\n 'the \"FLASK_APP\" environment variable, and a \"wsgi.py\" or '\n '\"app.py\" module was not found in the current directory.'\n )\n\n if self.set_debug_flag:\n # Update the app's debug flag through the descriptor so that\n # other values repopulate as well.\n app.debug = get_debug_flag()\n\n self._loaded_app = app\n return app"},{"col":0,"comment":"A test client for the app.","endLoc":38,"header":"@pytest.fixture\ndef client(app)","id":838,"name":"client","nodeType":"Function","startLoc":35,"text":"@pytest.fixture\ndef client(app):\n \"\"\"A test client for the app.\"\"\"\n return app.test_client()"},{"col":0,"comment":"Takes an app factory, a ``script_info` object and optionally a tuple\n of arguments. Checks for the existence of a script_info argument and calls\n the app_factory depending on that and the arguments provided.\n ","endLoc":119,"header":"def call_factory(script_info, app_factory, args=None, kwargs=None)","id":839,"name":"call_factory","nodeType":"Function","startLoc":89,"text":"def call_factory(script_info, app_factory, args=None, kwargs=None):\n \"\"\"Takes an app factory, a ``script_info` object and optionally a tuple\n of arguments. Checks for the existence of a script_info argument and calls\n the app_factory depending on that and the arguments provided.\n \"\"\"\n sig = inspect.signature(app_factory)\n args = [] if args is None else args\n kwargs = {} if kwargs is None else kwargs\n\n if \"script_info\" in sig.parameters:\n warnings.warn(\n \"The 'script_info' argument is deprecated and will not be\"\n \" passed to the app factory function in Flask 2.1.\",\n DeprecationWarning,\n )\n kwargs[\"script_info\"] = script_info\n\n if (\n not args\n and len(sig.parameters) == 1\n and next(iter(sig.parameters.values())).default is inspect.Parameter.empty\n ):\n warnings.warn(\n \"Script info is deprecated and will not be passed as the\"\n \" single argument to the app factory function in Flask\"\n \" 2.1.\",\n DeprecationWarning,\n )\n args.append(script_info)\n\n return app_factory(*args, **kwargs)"},{"className":"View","col":0,"comment":"Alternative way to use view functions. A subclass has to implement\n :meth:`dispatch_request` which is called with the view arguments from\n the URL routing system. If :attr:`methods` is provided the methods\n do not have to be passed to the :meth:`~flask.Flask.add_url_rule`\n method explicitly::\n\n class MyView(View):\n methods = ['GET']\n\n def dispatch_request(self, name):\n return f\"Hello {name}!\"\n\n app.add_url_rule('/hello/', view_func=MyView.as_view('myview'))\n\n When you want to decorate a pluggable view you will have to either do that\n when the view function is created (by wrapping the return value of\n :meth:`as_view`) or you can use the :attr:`decorators` attribute::\n\n class SecretView(View):\n methods = ['GET']\n decorators = [superuser_required]\n\n def dispatch_request(self):\n ...\n\n The decorators stored in the decorators list are applied one after another\n when the view function is created. Note that you can *not* use the class\n based decorators since those would decorate the view class and not the\n generated view function!\n ","endLoc":102,"id":840,"nodeType":"Class","startLoc":12,"text":"class View:\n \"\"\"Alternative way to use view functions. A subclass has to implement\n :meth:`dispatch_request` which is called with the view arguments from\n the URL routing system. If :attr:`methods` is provided the methods\n do not have to be passed to the :meth:`~flask.Flask.add_url_rule`\n method explicitly::\n\n class MyView(View):\n methods = ['GET']\n\n def dispatch_request(self, name):\n return f\"Hello {name}!\"\n\n app.add_url_rule('/hello/', view_func=MyView.as_view('myview'))\n\n When you want to decorate a pluggable view you will have to either do that\n when the view function is created (by wrapping the return value of\n :meth:`as_view`) or you can use the :attr:`decorators` attribute::\n\n class SecretView(View):\n methods = ['GET']\n decorators = [superuser_required]\n\n def dispatch_request(self):\n ...\n\n The decorators stored in the decorators list are applied one after another\n when the view function is created. Note that you can *not* use the class\n based decorators since those would decorate the view class and not the\n generated view function!\n \"\"\"\n\n #: A list of methods this view can handle.\n methods: t.Optional[t.List[str]] = None\n\n #: Setting this disables or force-enables the automatic options handling.\n provide_automatic_options: t.Optional[bool] = None\n\n #: The canonical way to decorate class-based views is to decorate the\n #: return value of as_view(). However since this moves parts of the\n #: logic from the class declaration to the place where it's hooked\n #: into the routing system.\n #:\n #: You can place one or more decorators in this list and whenever the\n #: view function is created the result is automatically decorated.\n #:\n #: .. versionadded:: 0.8\n decorators: t.List[t.Callable] = []\n\n def dispatch_request(self) -> ResponseReturnValue:\n \"\"\"Subclasses have to override this method to implement the\n actual view function code. This method is called with all\n the arguments from the URL rule.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> t.Callable:\n \"\"\"Converts the class into an actual view function that can be used\n with the routing system. Internally this generates a function on the\n fly which will instantiate the :class:`View` on each request and call\n the :meth:`dispatch_request` method on it.\n\n The arguments passed to :meth:`as_view` are forwarded to the\n constructor of the class.\n \"\"\"\n\n def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n self = view.view_class(*class_args, **class_kwargs) # type: ignore\n return self.dispatch_request(*args, **kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view"},{"col":4,"comment":"Subclasses have to override this method to implement the\n actual view function code. This method is called with all\n the arguments from the URL rule.\n ","endLoc":66,"header":"def dispatch_request(self) -> ResponseReturnValue","id":841,"name":"dispatch_request","nodeType":"Function","startLoc":61,"text":"def dispatch_request(self) -> ResponseReturnValue:\n \"\"\"Subclasses have to override this method to implement the\n actual view function code. This method is called with all\n the arguments from the URL rule.\n \"\"\"\n raise NotImplementedError()"},{"col":4,"comment":"Converts the class into an actual view function that can be used\n with the routing system. Internally this generates a function on the\n fly which will instantiate the :class:`View` on each request and call\n the :meth:`dispatch_request` method on it.\n\n The arguments passed to :meth:`as_view` are forwarded to the\n constructor of the class.\n ","endLoc":102,"header":"@classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> t.Callable","id":842,"name":"as_view","nodeType":"Function","startLoc":68,"text":"@classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> t.Callable:\n \"\"\"Converts the class into an actual view function that can be used\n with the routing system. Internally this generates a function on the\n fly which will instantiate the :class:`View` on each request and call\n the :meth:`dispatch_request` method on it.\n\n The arguments passed to :meth:`as_view` are forwarded to the\n constructor of the class.\n \"\"\"\n\n def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n self = view.view_class(*class_args, **class_kwargs) # type: ignore\n return self.dispatch_request(*args, **kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view"},{"col":0,"comment":"null","endLoc":54,"header":"@pytest.fixture\ndef app()","id":843,"name":"app","nodeType":"Function","startLoc":51,"text":"@pytest.fixture\ndef app():\n app = Flask(\"flask_test\", root_path=os.path.dirname(__file__))\n return app"},{"col":4,"comment":"Pops the request context and unbinds it by doing that. This will\n also trigger the execution of functions registered by the\n :meth:`~flask.Flask.teardown_request` decorator.\n\n .. versionchanged:: 0.9\n Added the `exc` argument.\n ","endLoc":449,"header":"def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None","id":844,"name":"pop","nodeType":"Function","startLoc":412,"text":"def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore\n \"\"\"Pops the request context and unbinds it by doing that. This will\n also trigger the execution of functions registered by the\n :meth:`~flask.Flask.teardown_request` decorator.\n\n .. versionchanged:: 0.9\n Added the `exc` argument.\n \"\"\"\n app_ctx = self._implicit_app_ctx_stack.pop()\n clear_request = False\n\n try:\n if not self._implicit_app_ctx_stack:\n self.preserved = False\n self._preserved_exc = None\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n self.app.do_teardown_request(exc)\n\n request_close = getattr(self.request, \"close\", None)\n if request_close is not None:\n request_close()\n clear_request = True\n finally:\n rv = _request_ctx_stack.pop()\n\n # get rid of circular dependencies at the end of the request\n # so that we don't require the GC to be active.\n if clear_request:\n rv.request.environ[\"werkzeug.request\"] = None\n\n # Get rid of the app as well if necessary.\n if app_ctx is not None:\n app_ctx.pop(exc)\n\n assert (\n rv is self\n ), f\"Popped wrong request context. ({rv!r} instead of {self!r})\""},{"col":0,"comment":"null","endLoc":60,"header":"@pytest.fixture\ndef app_ctx(app)","id":845,"name":"app_ctx","nodeType":"Function","startLoc":57,"text":"@pytest.fixture\ndef app_ctx(app):\n with app.app_context() as ctx:\n yield ctx"},{"col":0,"comment":"Given a filename this will try to calculate the python path, add it\n to the search path and return the actual module name that is expected.\n ","endLoc":249,"header":"def prepare_import(path)","id":846,"name":"prepare_import","nodeType":"Function","startLoc":223,"text":"def prepare_import(path):\n \"\"\"Given a filename this will try to calculate the python path, add it\n to the search path and return the actual module name that is expected.\n \"\"\"\n path = os.path.realpath(path)\n\n fname, ext = os.path.splitext(path)\n if ext == \".py\":\n path = fname\n\n if os.path.basename(path) == \"__init__\":\n path = os.path.dirname(path)\n\n module_name = []\n\n # move up until outside package structure (no __init__.py)\n while True:\n path, name = os.path.split(path)\n module_name.append(name)\n\n if not os.path.exists(os.path.join(path, \"__init__.py\")):\n break\n\n if sys.path[0] != path:\n sys.path.insert(0, path)\n\n return \".\".join(module_name[::-1])"},{"col":4,"comment":"null","endLoc":458,"header":"def auto_pop(self, exc: t.Optional[BaseException]) -> None","id":847,"name":"auto_pop","nodeType":"Function","startLoc":451,"text":"def auto_pop(self, exc: t.Optional[BaseException]) -> None:\n if self.request.environ.get(\"flask._preserve_context\") or (\n exc is not None and self.app.preserve_context_on_exception\n ):\n self.preserved = True\n self._preserved_exc = exc # type: ignore\n else:\n self.pop(exc)"},{"col":0,"comment":"A test runner for the app's Click commands.","endLoc":44,"header":"@pytest.fixture\ndef runner(app)","id":848,"name":"runner","nodeType":"Function","startLoc":41,"text":"@pytest.fixture\ndef runner(app):\n \"\"\"A test runner for the app's Click commands.\"\"\"\n return app.test_cli_runner()"},{"col":0,"comment":"null","endLoc":66,"header":"@pytest.fixture\ndef req_ctx(app)","id":849,"name":"req_ctx","nodeType":"Function","startLoc":63,"text":"@pytest.fixture\ndef req_ctx(app):\n with app.test_request_context() as ctx:\n yield ctx"},{"col":0,"comment":"null","endLoc":62,"header":"@pytest.fixture\ndef auth(client)","id":850,"name":"auth","nodeType":"Function","startLoc":60,"text":"@pytest.fixture\ndef auth(client):\n return AuthActions(client)"},{"col":0,"comment":"null","endLoc":71,"header":"@pytest.fixture\ndef client(app)","id":851,"name":"client","nodeType":"Function","startLoc":69,"text":"@pytest.fixture\ndef client(app):\n return app.test_client()"},{"col":0,"comment":"null","endLoc":275,"header":"def locate_app(script_info, module_name, app_name, raise_if_not_found=True)","id":852,"name":"locate_app","nodeType":"Function","startLoc":252,"text":"def locate_app(script_info, module_name, app_name, raise_if_not_found=True):\n __traceback_hide__ = True # noqa: F841\n\n try:\n __import__(module_name)\n except ImportError:\n # Reraise the ImportError if it occurred within the imported module.\n # Determine this by checking whether the trace has a depth > 1.\n if sys.exc_info()[2].tb_next:\n raise NoAppException(\n f\"While importing {module_name!r}, an ImportError was\"\n f\" raised:\\n\\n{traceback.format_exc()}\"\n )\n elif raise_if_not_found:\n raise NoAppException(f\"Could not import {module_name!r}.\")\n else:\n return\n\n module = sys.modules[module_name]\n\n if app_name is None:\n return find_best_app(script_info, module)\n else:\n return find_app_by_string(script_info, module, app_name)"},{"attributeType":"null","col":72,"comment":"null","endLoc":11,"id":853,"name":"f","nodeType":"Attribute","startLoc":11,"text":"f"},{"col":0,"comment":"null","endLoc":84,"header":"@pytest.fixture\ndef test_apps(monkeypatch)","id":854,"name":"test_apps","nodeType":"Function","startLoc":74,"text":"@pytest.fixture\ndef test_apps(monkeypatch):\n monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), \"test_apps\"))\n original_modules = set(sys.modules.keys())\n\n yield\n\n # Remove any imports cached during the test. Otherwise \"import app\"\n # will work in the next test even though it's no longer on the path.\n for key in sys.modules.keys() - original_modules:\n sys.modules.pop(key)"},{"attributeType":"null","col":4,"comment":"null","endLoc":12,"id":855,"name":"_data_sql","nodeType":"Attribute","startLoc":12,"text":"_data_sql"},{"col":0,"comment":"","endLoc":1,"header":"conftest.py#","id":856,"name":"","nodeType":"Function","startLoc":1,"text":"with open(os.path.join(os.path.dirname(__file__), \"data.sql\"), \"rb\") as f:\n _data_sql = f.read().decode(\"utf8\")"},{"id":857,"name":"install.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Make the Project Installable\n============================\n\nMaking your project installable means that you can build a\n*distribution* file and install that in another environment, just like\nyou installed Flask in your project's environment. This makes deploying\nyour project the same as installing any other library, so you're using\nall the standard Python tools to manage everything.\n\nInstalling also comes with other benefits that might not be obvious from\nthe tutorial or as a new Python user, including:\n\n* Currently, Python and Flask understand how to use the ``flaskr``\n package only because you're running from your project's directory.\n Installing means you can import it no matter where you run from.\n\n* You can manage your project's dependencies just like other packages\n do, so ``pip install yourproject.whl`` installs them.\n\n* Test tools can isolate your test environment from your development\n environment.\n\n.. note::\n This is being introduced late in the tutorial, but in your future\n projects you should always start with this.\n\n\nDescribe the Project\n--------------------\n\nThe ``setup.py`` file describes your project and the files that belong\nto it.\n\n.. code-block:: python\n :caption: ``setup.py``\n\n from setuptools import find_packages, setup\n\n setup(\n name='flaskr',\n version='1.0.0',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'flask',\n ],\n )\n\n\n``packages`` tells Python what package directories (and the Python files\nthey contain) to include. ``find_packages()`` finds these directories\nautomatically so you don't have to type them out. To include other\nfiles, such as the static and templates directories,\n``include_package_data`` is set. Python needs another file named\n``MANIFEST.in`` to tell what this other data is.\n\n.. code-block:: none\n :caption: ``MANIFEST.in``\n\n include flaskr/schema.sql\n graft flaskr/static\n graft flaskr/templates\n global-exclude *.pyc\n\nThis tells Python to copy everything in the ``static`` and ``templates``\ndirectories, and the ``schema.sql`` file, but to exclude all bytecode\nfiles.\n\nSee the `official packaging guide`_ for another explanation of the files\nand options used.\n\n.. _official packaging guide: https://packaging.python.org/tutorials/packaging-projects/\n\n\nInstall the Project\n-------------------\n\nUse ``pip`` to install your project in the virtual environment.\n\n.. code-block:: none\n\n $ pip install -e .\n\nThis tells pip to find ``setup.py`` in the current directory and install\nit in *editable* or *development* mode. Editable mode means that as you\nmake changes to your local code, you'll only need to re-install if you\nchange the metadata about the project, such as its dependencies.\n\nYou can observe that the project is now installed with ``pip list``.\n\n.. code-block:: none\n\n $ pip list\n\n Package Version Location\n -------------- --------- ----------------------------------\n click 6.7\n Flask 1.0\n flaskr 1.0.0 /home/user/Projects/flask-tutorial\n itsdangerous 0.24\n Jinja2 2.10\n MarkupSafe 1.0\n pip 9.0.3\n setuptools 39.0.1\n Werkzeug 0.14.1\n wheel 0.30.0\n\nNothing changes from how you've been running your project so far.\n``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs\nthe application, but you can call it from anywhere, not just the\n``flask-tutorial`` directory.\n\nContinue to :doc:`tests`.\n"},{"col":0,"comment":"Given a module instance this tries to find the best possible\n application in the module or raises an exception.\n ","endLoc":86,"header":"def find_best_app(script_info, module)","id":858,"name":"find_best_app","nodeType":"Function","startLoc":37,"text":"def find_best_app(script_info, module):\n \"\"\"Given a module instance this tries to find the best possible\n application in the module or raises an exception.\n \"\"\"\n from . import Flask\n\n # Search for the most common names first.\n for attr_name in (\"app\", \"application\"):\n app = getattr(module, attr_name, None)\n\n if isinstance(app, Flask):\n return app\n\n # Otherwise find the only object that is a Flask instance.\n matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]\n\n if len(matches) == 1:\n return matches[0]\n elif len(matches) > 1:\n raise NoAppException(\n \"Detected multiple Flask applications in module\"\n f\" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'\"\n f\" to specify the correct one.\"\n )\n\n # Search for app factory functions.\n for attr_name in (\"create_app\", \"make_app\"):\n app_factory = getattr(module, attr_name, None)\n\n if inspect.isfunction(app_factory):\n try:\n app = call_factory(script_info, app_factory)\n\n if isinstance(app, Flask):\n return app\n except TypeError:\n if not _called_with_wrong_args(app_factory):\n raise\n raise NoAppException(\n f\"Detected factory {attr_name!r} in module {module.__name__!r},\"\n \" but could not call it without arguments. Use\"\n f\" \\\"FLASK_APP='{module.__name__}:{attr_name}(args)'\\\"\"\n \" to specify arguments.\"\n )\n\n raise NoAppException(\n \"Failed to find Flask application or factory in module\"\n f\" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'\"\n \" to specify one.\"\n )"},{"fileName":"__main__.py","filePath":"src/flask","id":859,"nodeType":"File","text":"from .cli import main\n\nmain()\n"},{"col":0,"comment":"null","endLoc":990,"header":"def main() -> None","id":860,"name":"main","nodeType":"Function","startLoc":981,"text":"def main() -> None:\n if int(click.__version__[0]) < 8:\n warnings.warn(\n \"Using the `flask` cli with Click 7 is deprecated and\"\n \" will not be supported starting with Flask 2.1.\"\n \" Please upgrade to Click 8 as soon as possible.\",\n DeprecationWarning,\n )\n # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed\n cli.main(args=sys.argv[1:])"},{"col":0,"comment":"null","endLoc":96,"header":"@pytest.fixture(autouse=True)\ndef leak_detector()","id":861,"name":"leak_detector","nodeType":"Function","startLoc":87,"text":"@pytest.fixture(autouse=True)\ndef leak_detector():\n yield\n\n # make sure we're not leaking a request context since we are\n # testing flask internally in debug mode in a few cases\n leaks = []\n while flask._request_ctx_stack.top is not None:\n leaks.append(flask._request_ctx_stack.pop())\n assert leaks == []"},{"col":0,"comment":"Patch pkgutil.get_loader to give loader without get_filename or archive.\n\n This provides for tests where a system has custom loaders, e.g. Google App\n Engine's HardenedModulesHook, which have neither the `get_filename` method\n nor the `archive` attribute.\n\n This fixture will run the testcase twice, once with and once without the\n limitation/mock.\n ","endLoc":127,"header":"@pytest.fixture(params=(True, False))\ndef limit_loader(request, monkeypatch)","id":862,"name":"limit_loader","nodeType":"Function","startLoc":99,"text":"@pytest.fixture(params=(True, False))\ndef limit_loader(request, monkeypatch):\n \"\"\"Patch pkgutil.get_loader to give loader without get_filename or archive.\n\n This provides for tests where a system has custom loaders, e.g. Google App\n Engine's HardenedModulesHook, which have neither the `get_filename` method\n nor the `archive` attribute.\n\n This fixture will run the testcase twice, once with and once without the\n limitation/mock.\n \"\"\"\n if not request.param:\n return\n\n class LimitedLoader:\n def __init__(self, loader):\n self.loader = loader\n\n def __getattr__(self, name):\n if name in {\"archive\", \"get_filename\"}:\n raise AttributeError(f\"Mocking a loader which does not have {name!r}.\")\n return getattr(self.loader, name)\n\n old_get_loader = pkgutil.get_loader\n\n def get_loader(*args, **kwargs):\n return LimitedLoader(old_get_loader(*args, **kwargs))\n\n monkeypatch.setattr(pkgutil, \"get_loader\", get_loader)"},{"col":0,"comment":"","endLoc":1,"header":"__main__.py#","id":863,"name":"","nodeType":"Function","startLoc":1,"text":"main()"},{"id":864,"name":"index.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Tutorial\n========\n\n.. toctree::\n :caption: Contents:\n :maxdepth: 1\n\n layout\n factory\n database\n views\n templates\n static\n blog\n install\n tests\n deploy\n next\n\nThis tutorial will walk you through creating a basic blog application\ncalled Flaskr. Users will be able to register, log in, create posts,\nand edit or delete their own posts. You will be able to package and\ninstall the application on other computers.\n\n.. image:: flaskr_index.png\n :align: center\n :class: screenshot\n :alt: screenshot of index page\n\nIt's assumed that you're already familiar with Python. The `official\ntutorial`_ in the Python docs is a great way to learn or review first.\n\n.. _official tutorial: https://docs.python.org/3/tutorial/\n\nWhile it's designed to give a good starting point, the tutorial doesn't\ncover all of Flask's features. Check out the :doc:`/quickstart` for an\noverview of what Flask can do, then dive into the docs to find out more.\nThe tutorial only uses what's provided by Flask and Python. In another\nproject, you might decide to use :doc:`/extensions` or other libraries\nto make some tasks simpler.\n\n.. image:: flaskr_login.png\n :align: center\n :class: screenshot\n :alt: screenshot of login page\n\nFlask is flexible. It doesn't require you to use any particular project\nor code layout. However, when first starting, it's helpful to use a more\nstructured approach. This means that the tutorial will require a bit of\nboilerplate up front, but it's done to avoid many common pitfalls that\nnew developers encounter, and it creates a project that's easy to expand\non. Once you become more comfortable with Flask, you can step out of\nthis structure and take full advantage of Flask's flexibility.\n\n.. image:: flaskr_edit.png\n :align: center\n :class: screenshot\n :alt: screenshot of login page\n\n:gh:`The tutorial project is available as an example in the Flask\nrepository `, if you want to compare your project\nwith the final product as you follow the tutorial.\n\nContinue to :doc:`layout`.\n"},{"id":865,"name":"tests/test_apps/blueprintapp/apps/frontend/templates/frontend","nodeType":"Package"},{"id":866,"name":"index.html","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/frontend/templates/frontend","text":"Hello from the Frontend\n"},{"id":867,"name":"tests/test_apps/blueprintapp/apps/admin/templates/admin","nodeType":"Package"},{"id":868,"name":"index.html","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/admin/templates/admin","text":"Hello from the Admin\n"},{"id":869,"name":"escaping_template.html","nodeType":"TextFile","path":"tests/templates","text":"{{ text }}\n{{ html }}\n{% autoescape false %}{{ text }}\n{{ html }}{% endautoescape %}\n{% autoescape true %}{{ text }}\n{{ html }}{% endautoescape %}\n"},{"id":870,"name":"flashing.rst","nodeType":"TextFile","path":"docs/patterns","text":"Message Flashing\n================\n\nGood applications and user interfaces are all about feedback. If the user\ndoes not get enough feedback they will probably end up hating the\napplication. Flask provides a really simple way to give feedback to a\nuser with the flashing system. The flashing system basically makes it\npossible to record a message at the end of a request and access it next\nrequest and only next request. This is usually combined with a layout\ntemplate that does this. Note that browsers and sometimes web servers enforce\na limit on cookie sizes. This means that flashing messages that are too\nlarge for session cookies causes message flashing to fail silently.\n\nSimple Flashing\n---------------\n\nSo here is a full example::\n\n from flask import Flask, flash, redirect, render_template, \\\n request, url_for\n\n app = Flask(__name__)\n app.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\n @app.route('/')\n def index():\n return render_template('index.html')\n\n @app.route('/login', methods=['GET', 'POST'])\n def login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'secret':\n error = 'Invalid credentials'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n return render_template('login.html', error=error)\n\nAnd here is the :file:`layout.html` template which does the magic:\n\n.. sourcecode:: html+jinja\n\n \n My Application\n {% with messages = get_flashed_messages() %}\n {% if messages %}\n
    \n {% for message in messages %}\n
  • {{ message }}
  • \n {% endfor %}\n
\n {% endif %}\n {% endwith %}\n {% block body %}{% endblock %}\n\nHere is the :file:`index.html` template which inherits from :file:`layout.html`:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block body %}\n

Overview

\n

Do you want to log in?\n {% endblock %}\n\nAnd here is the :file:`login.html` template which also inherits from\n:file:`layout.html`:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block body %}\n

Login

\n {% if error %}\n

Error: {{ error }}\n {% endif %}\n

\n
\n
Username:\n
\n
Password:\n
\n
\n

\n

\n {% endblock %}\n\nFlashing With Categories\n------------------------\n\n.. versionadded:: 0.3\n\nIt is also possible to provide categories when flashing a message. The\ndefault category if nothing is provided is ``'message'``. Alternative\ncategories can be used to give the user better feedback. For example\nerror messages could be displayed with a red background.\n\nTo flash a message with a different category, just use the second argument\nto the :func:`~flask.flash` function::\n\n flash('Invalid password provided', 'error')\n\nInside the template you then have to tell the\n:func:`~flask.get_flashed_messages` function to also return the\ncategories. The loop looks slightly different in that situation then:\n\n.. sourcecode:: html+jinja\n\n {% with messages = get_flashed_messages(with_categories=true) %}\n {% if messages %}\n
    \n {% for category, message in messages %}\n
  • {{ message }}
  • \n {% endfor %}\n
\n {% endif %}\n {% endwith %}\n\nThis is just one example of how to render these flashed messages. One\nmight also use the category to add a prefix such as\n``Error:`` to the message.\n\nFiltering Flash Messages\n------------------------\n\n.. versionadded:: 0.9\n\nOptionally you can pass a list of categories which filters the results of\n:func:`~flask.get_flashed_messages`. This is useful if you wish to\nrender each category in a separate block.\n\n.. sourcecode:: html+jinja\n\n {% with errors = get_flashed_messages(category_filter=[\"error\"]) %}\n {% if errors %}\n
\n ×\n
    \n {%- for msg in errors %}\n
  • {{ msg }}
  • \n {% endfor -%}\n
\n
\n {% endif %}\n {% endwith %}\n"},{"id":871,"name":"README.rst","nodeType":"TextFile","path":"","text":"Flask\n=====\n\nFlask is a lightweight `WSGI`_ web application framework. It is designed\nto make getting started quick and easy, with the ability to scale up to\ncomplex applications. It began as a simple wrapper around `Werkzeug`_\nand `Jinja`_ and has become one of the most popular Python web\napplication frameworks.\n\nFlask offers suggestions, but doesn't enforce any dependencies or\nproject layout. It is up to the developer to choose the tools and\nlibraries they want to use. There are many extensions provided by the\ncommunity that make adding new functionality easy.\n\n.. _WSGI: https://wsgi.readthedocs.io/\n.. _Werkzeug: https://werkzeug.palletsprojects.com/\n.. _Jinja: https://jinja.palletsprojects.com/\n\n\nInstalling\n----------\n\nInstall and update using `pip`_:\n\n.. code-block:: text\n\n $ pip install -U Flask\n\n.. _pip: https://pip.pypa.io/en/stable/quickstart/\n\n\nA Simple Example\n----------------\n\n.. code-block:: python\n\n # save this as app.py\n from flask import Flask\n\n app = Flask(__name__)\n\n @app.route(\"/\")\n def hello():\n return \"Hello, World!\"\n\n.. code-block:: text\n\n $ flask run\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n\n\nContributing\n------------\n\nFor guidance on setting up a development environment and how to make a\ncontribution to Flask, see the `contributing guidelines`_.\n\n.. _contributing guidelines: https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst\n\n\nDonate\n------\n\nThe Pallets organization develops and supports Flask and the libraries\nit uses. In order to grow the community of contributors and users, and\nallow the maintainers to devote more time to the projects, `please\ndonate today`_.\n\n.. _please donate today: https://palletsprojects.com/donate\n\n\nLinks\n-----\n\n- Documentation: https://flask.palletsprojects.com/\n- Changes: https://flask.palletsprojects.com/changes/\n- PyPI Releases: https://pypi.org/project/Flask/\n- Source Code: https://github.com/pallets/flask/\n- Issue Tracker: https://github.com/pallets/flask/issues/\n- Website: https://palletsprojects.com/p/flask/\n- Twitter: https://twitter.com/PalletsTeam\n- Chat: https://discord.gg/pallets\n"},{"id":872,"name":"viewdecorators.rst","nodeType":"TextFile","path":"docs/patterns","text":"View Decorators\n===============\n\nPython has a really interesting feature called function decorators. This\nallows some really neat things for web applications. Because each view in\nFlask is a function, decorators can be used to inject additional\nfunctionality to one or more functions. The :meth:`~flask.Flask.route`\ndecorator is the one you probably used already. But there are use cases\nfor implementing your own decorator. For instance, imagine you have a\nview that should only be used by people that are logged in. If a user\ngoes to the site and is not logged in, they should be redirected to the\nlogin page. This is a good example of a use case where a decorator is an\nexcellent solution.\n\nLogin Required Decorator\n------------------------\n\nSo let's implement such a decorator. A decorator is a function that\nwraps and replaces another function. Since the original function is\nreplaced, you need to remember to copy the original function's information\nto the new function. Use :func:`functools.wraps` to handle this for you.\n\nThis example assumes that the login page is called ``'login'`` and that\nthe current user is stored in ``g.user`` and is ``None`` if there is no-one\nlogged in. ::\n\n from functools import wraps\n from flask import g, request, redirect, url_for\n\n def login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if g.user is None:\n return redirect(url_for('login', next=request.url))\n return f(*args, **kwargs)\n return decorated_function\n\nTo use the decorator, apply it as innermost decorator to a view function.\nWhen applying further decorators, always remember\nthat the :meth:`~flask.Flask.route` decorator is the outermost. ::\n\n @app.route('/secret_page')\n @login_required\n def secret_page():\n pass\n\n.. note::\n The ``next`` value will exist in ``request.args`` after a ``GET`` request for\n the login page. You'll have to pass it along when sending the ``POST`` request\n from the login form. You can do this with a hidden input tag, then retrieve it\n from ``request.form`` when logging the user in. ::\n\n \n\n\nCaching Decorator\n-----------------\n\nImagine you have a view function that does an expensive calculation and\nbecause of that you would like to cache the generated results for a\ncertain amount of time. A decorator would be nice for that. We're\nassuming you have set up a cache like mentioned in :doc:`caching`.\n\nHere is an example cache function. It generates the cache key from a\nspecific prefix (actually a format string) and the current path of the\nrequest. Notice that we are using a function that first creates the\ndecorator that then decorates the function. Sounds awful? Unfortunately\nit is a little bit more complex, but the code should still be\nstraightforward to read.\n\nThe decorated function will then work as follows\n\n1. get the unique cache key for the current request based on the current\n path.\n2. get the value for that key from the cache. If the cache returned\n something we will return that value.\n3. otherwise the original function is called and the return value is\n stored in the cache for the timeout provided (by default 5 minutes).\n\nHere the code::\n\n from functools import wraps\n from flask import request\n\n def cached(timeout=5 * 60, key='view/{}'):\n def decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n cache_key = key.format(request.path)\n rv = cache.get(cache_key)\n if rv is not None:\n return rv\n rv = f(*args, **kwargs)\n cache.set(cache_key, rv, timeout=timeout)\n return rv\n return decorated_function\n return decorator\n\nNotice that this assumes an instantiated ``cache`` object is available, see\n:doc:`caching`.\n\n\nTemplating Decorator\n--------------------\n\nA common pattern invented by the TurboGears guys a while back is a\ntemplating decorator. The idea of that decorator is that you return a\ndictionary with the values passed to the template from the view function\nand the template is automatically rendered. With that, the following\nthree examples do exactly the same::\n\n @app.route('/')\n def index():\n return render_template('index.html', value=42)\n\n @app.route('/')\n @templated('index.html')\n def index():\n return dict(value=42)\n\n @app.route('/')\n @templated()\n def index():\n return dict(value=42)\n\nAs you can see, if no template name is provided it will use the endpoint\nof the URL map with dots converted to slashes + ``'.html'``. Otherwise\nthe provided template name is used. When the decorated function returns,\nthe dictionary returned is passed to the template rendering function. If\n``None`` is returned, an empty dictionary is assumed, if something else than\na dictionary is returned we return it from the function unchanged. That\nway you can still use the redirect function or return simple strings.\n\nHere is the code for that decorator::\n\n from functools import wraps\n from flask import request, render_template\n\n def templated(template=None):\n def decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n template_name = template\n if template_name is None:\n template_name = f\"'{request.endpoint.replace('.', '/')}.html'\"\n ctx = f(*args, **kwargs)\n if ctx is None:\n ctx = {}\n elif not isinstance(ctx, dict):\n return ctx\n return render_template(template_name, **ctx)\n return decorated_function\n return decorator\n\n\nEndpoint Decorator\n------------------\n\nWhen you want to use the werkzeug routing system for more flexibility you\nneed to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`\nto a view function. This is possible with this decorator. For example::\n\n from flask import Flask\n from werkzeug.routing import Rule\n\n app = Flask(__name__)\n app.url_map.add(Rule('/', endpoint='index'))\n\n @app.endpoint('index')\n def my_index():\n return \"Hello world\"\n"},{"fileName":"app.py","filePath":"src/flask","id":873,"nodeType":"File","text":"import functools\nimport inspect\nimport logging\nimport os\nimport sys\nimport typing as t\nimport weakref\nfrom datetime import timedelta\nfrom itertools import chain\nfrom threading import Lock\nfrom types import TracebackType\n\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.local import ContextVar\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import Map\nfrom werkzeug.routing import MapAdapter\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.routing import RoutingException\nfrom werkzeug.routing import Rule\nfrom werkzeug.wrappers import Response as BaseResponse\n\nfrom . import cli\nfrom . import json\nfrom .config import Config\nfrom .config import ConfigAttribute\nfrom .ctx import _AppCtxGlobals\nfrom .ctx import AppContext\nfrom .ctx import RequestContext\nfrom .globals import _request_ctx_stack\nfrom .globals import g\nfrom .globals import request\nfrom .globals import session\nfrom .helpers import get_debug_flag\nfrom .helpers import get_env\nfrom .helpers import get_flashed_messages\nfrom .helpers import get_load_dotenv\nfrom .helpers import locked_cached_property\nfrom .helpers import url_for\nfrom .json import jsonify\nfrom .logging import create_logger\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import find_package\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\nfrom .sessions import SecureCookieSessionInterface\nfrom .signals import appcontext_tearing_down\nfrom .signals import got_request_exception\nfrom .signals import request_finished\nfrom .signals import request_started\nfrom .signals import request_tearing_down\nfrom .templating import DispatchingJinjaLoader\nfrom .templating import Environment\nfrom .typing import AfterRequestCallable\nfrom .typing import BeforeRequestCallable\nfrom .typing import ErrorHandlerCallable\nfrom .typing import ResponseReturnValue\nfrom .typing import TeardownCallable\nfrom .typing import TemplateContextProcessorCallable\nfrom .typing import TemplateFilterCallable\nfrom .typing import TemplateGlobalCallable\nfrom .typing import TemplateTestCallable\nfrom .typing import URLDefaultCallable\nfrom .typing import URLValuePreprocessorCallable\nfrom .wrappers import Request\nfrom .wrappers import Response\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n from .blueprints import Blueprint\n from .testing import FlaskClient\n from .testing import FlaskCliRunner\n\nif sys.version_info >= (3, 8):\n iscoroutinefunction = inspect.iscoroutinefunction\nelse:\n\n def iscoroutinefunction(func: t.Any) -> bool:\n while inspect.ismethod(func):\n func = func.__func__\n\n while isinstance(func, functools.partial):\n func = func.func\n\n return inspect.iscoroutinefunction(func)\n\n\ndef _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:\n if value is None or isinstance(value, timedelta):\n return value\n\n return timedelta(seconds=value)\n\n\nclass Flask(Scaffold):\n \"\"\"The flask object implements a WSGI application and acts as the central\n object. It is passed the name of the module or package of the\n application. Once it is created it will act as a central registry for\n the view functions, the URL rules, template configuration and much more.\n\n The name of the package is used to resolve resources from inside the\n package or the folder the module is contained in depending on if the\n package parameter resolves to an actual python package (a folder with\n an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n For more information about resource loading, see :func:`open_resource`.\n\n Usually you create a :class:`Flask` instance in your main module or\n in the :file:`__init__.py` file of your package like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n .. admonition:: About the First Parameter\n\n The idea of the first parameter is to give Flask an idea of what\n belongs to your application. This name is used to find resources\n on the filesystem, can be used by extensions to improve debugging\n information and a lot more.\n\n So it's important what you provide there. If you are using a single\n module, `__name__` is always the correct value. If you however are\n using a package, it's usually recommended to hardcode the name of\n your package there.\n\n For example if your application is defined in :file:`yourapplication/app.py`\n you should create it with one of the two versions below::\n\n app = Flask('yourapplication')\n app = Flask(__name__.split('.')[0])\n\n Why is that? The application will work even with `__name__`, thanks\n to how resources are looked up. However it will make debugging more\n painful. Certain extensions can make assumptions based on the\n import name of your application. For example the Flask-SQLAlchemy\n extension will look for the code in your application that triggered\n an SQL query in debug mode. If the import name is not properly set\n up, that debugging information is lost. (For example it would only\n pick up SQL queries in `yourapplication.app` and not\n `yourapplication.views.frontend`)\n\n .. versionadded:: 0.7\n The `static_url_path`, `static_folder`, and `template_folder`\n parameters were added.\n\n .. versionadded:: 0.8\n The `instance_path` and `instance_relative_config` parameters were\n added.\n\n .. versionadded:: 0.11\n The `root_path` parameter was added.\n\n .. versionadded:: 1.0\n The ``host_matching`` and ``static_host`` parameters were added.\n\n .. versionadded:: 1.0\n The ``subdomain_matching`` parameter was added. Subdomain\n matching needs to be enabled manually now. Setting\n :data:`SERVER_NAME` does not implicitly enable it.\n\n :param import_name: the name of the application package\n :param static_url_path: can be used to specify a different path for the\n static files on the web. Defaults to the name\n of the `static_folder` folder.\n :param static_folder: The folder with static files that is served at\n ``static_url_path``. Relative to the application ``root_path``\n or an absolute path. Defaults to ``'static'``.\n :param static_host: the host to use when adding the static route.\n Defaults to None. Required when using ``host_matching=True``\n with a ``static_folder`` configured.\n :param host_matching: set ``url_map.host_matching`` attribute.\n Defaults to False.\n :param subdomain_matching: consider the subdomain relative to\n :data:`SERVER_NAME` when matching routes. Defaults to False.\n :param template_folder: the folder that contains the templates that should\n be used by the application. Defaults to\n ``'templates'`` folder in the root path of the\n application.\n :param instance_path: An alternative instance path for the application.\n By default the folder ``'instance'`` next to the\n package or module is assumed to be the instance\n path.\n :param instance_relative_config: if set to ``True`` relative filenames\n for loading the config are assumed to\n be relative to the instance path instead\n of the application root.\n :param root_path: The path to the root of the application files.\n This should only be set manually when it can't be detected\n automatically, such as for namespace packages.\n \"\"\"\n\n #: The class that is used for request objects. See :class:`~flask.Request`\n #: for more information.\n request_class = Request\n\n #: The class that is used for response objects. See\n #: :class:`~flask.Response` for more information.\n response_class = Response\n\n #: The class that is used for the Jinja environment.\n #:\n #: .. versionadded:: 0.11\n jinja_environment = Environment\n\n #: The class that is used for the :data:`~flask.g` instance.\n #:\n #: Example use cases for a custom class:\n #:\n #: 1. Store arbitrary attributes on flask.g.\n #: 2. Add a property for lazy per-request database connectors.\n #: 3. Return None instead of AttributeError on unexpected attributes.\n #: 4. Raise exception if an unexpected attr is set, a \"controlled\" flask.g.\n #:\n #: In Flask 0.9 this property was called `request_globals_class` but it\n #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the\n #: flask.g object is now application context scoped.\n #:\n #: .. versionadded:: 0.10\n app_ctx_globals_class = _AppCtxGlobals\n\n #: The class that is used for the ``config`` attribute of this app.\n #: Defaults to :class:`~flask.Config`.\n #:\n #: Example use cases for a custom class:\n #:\n #: 1. Default values for certain config options.\n #: 2. Access to config values through attributes in addition to keys.\n #:\n #: .. versionadded:: 0.11\n config_class = Config\n\n #: The testing flag. Set this to ``True`` to enable the test mode of\n #: Flask extensions (and in the future probably also Flask itself).\n #: For example this might activate test helpers that have an\n #: additional runtime cost which should not be enabled by default.\n #:\n #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the\n #: default it's implicitly enabled.\n #:\n #: This attribute can also be configured from the config with the\n #: ``TESTING`` configuration key. Defaults to ``False``.\n testing = ConfigAttribute(\"TESTING\")\n\n #: If a secret key is set, cryptographic components can use this to\n #: sign cookies and other things. Set this to a complex random value\n #: when you want to use the secure cookie for instance.\n #:\n #: This attribute can also be configured from the config with the\n #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.\n secret_key = ConfigAttribute(\"SECRET_KEY\")\n\n #: The secure cookie uses this for the name of the session cookie.\n #:\n #: This attribute can also be configured from the config with the\n #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``\n session_cookie_name = ConfigAttribute(\"SESSION_COOKIE_NAME\")\n\n #: A :class:`~datetime.timedelta` which is used to set the expiration\n #: date of a permanent session. The default is 31 days which makes a\n #: permanent session survive for roughly one month.\n #:\n #: This attribute can also be configured from the config with the\n #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to\n #: ``timedelta(days=31)``\n permanent_session_lifetime = ConfigAttribute(\n \"PERMANENT_SESSION_LIFETIME\", get_converter=_make_timedelta\n )\n\n #: A :class:`~datetime.timedelta` or number of seconds which is used\n #: as the default ``max_age`` for :func:`send_file`. The default is\n #: ``None``, which tells the browser to use conditional requests\n #: instead of a timed cache.\n #:\n #: Configured with the :data:`SEND_FILE_MAX_AGE_DEFAULT`\n #: configuration key.\n #:\n #: .. versionchanged:: 2.0\n #: Defaults to ``None`` instead of 12 hours.\n send_file_max_age_default = ConfigAttribute(\n \"SEND_FILE_MAX_AGE_DEFAULT\", get_converter=_make_timedelta\n )\n\n #: Enable this if you want to use the X-Sendfile feature. Keep in\n #: mind that the server has to support this. This only affects files\n #: sent with the :func:`send_file` method.\n #:\n #: .. versionadded:: 0.2\n #:\n #: This attribute can also be configured from the config with the\n #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.\n use_x_sendfile = ConfigAttribute(\"USE_X_SENDFILE\")\n\n #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.\n #:\n #: .. versionadded:: 0.10\n json_encoder = json.JSONEncoder\n\n #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.\n #:\n #: .. versionadded:: 0.10\n json_decoder = json.JSONDecoder\n\n #: Options that are passed to the Jinja environment in\n #: :meth:`create_jinja_environment`. Changing these options after\n #: the environment is created (accessing :attr:`jinja_env`) will\n #: have no effect.\n #:\n #: .. versionchanged:: 1.1.0\n #: This is a ``dict`` instead of an ``ImmutableDict`` to allow\n #: easier configuration.\n #:\n jinja_options: dict = {}\n\n #: Default configuration parameters.\n default_config = ImmutableDict(\n {\n \"ENV\": None,\n \"DEBUG\": None,\n \"TESTING\": False,\n \"PROPAGATE_EXCEPTIONS\": None,\n \"PRESERVE_CONTEXT_ON_EXCEPTION\": None,\n \"SECRET_KEY\": None,\n \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n \"USE_X_SENDFILE\": False,\n \"SERVER_NAME\": None,\n \"APPLICATION_ROOT\": \"/\",\n \"SESSION_COOKIE_NAME\": \"session\",\n \"SESSION_COOKIE_DOMAIN\": None,\n \"SESSION_COOKIE_PATH\": None,\n \"SESSION_COOKIE_HTTPONLY\": True,\n \"SESSION_COOKIE_SECURE\": False,\n \"SESSION_COOKIE_SAMESITE\": None,\n \"SESSION_REFRESH_EACH_REQUEST\": True,\n \"MAX_CONTENT_LENGTH\": None,\n \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n \"TRAP_BAD_REQUEST_ERRORS\": None,\n \"TRAP_HTTP_EXCEPTIONS\": False,\n \"EXPLAIN_TEMPLATE_LOADING\": False,\n \"PREFERRED_URL_SCHEME\": \"http\",\n \"JSON_AS_ASCII\": True,\n \"JSON_SORT_KEYS\": True,\n \"JSONIFY_PRETTYPRINT_REGULAR\": False,\n \"JSONIFY_MIMETYPE\": \"application/json\",\n \"TEMPLATES_AUTO_RELOAD\": None,\n \"MAX_COOKIE_SIZE\": 4093,\n }\n )\n\n #: The rule object to use for URL rules created. This is used by\n #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.\n #:\n #: .. versionadded:: 0.7\n url_rule_class = Rule\n\n #: The map object to use for storing the URL rules and routing\n #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.\n #:\n #: .. versionadded:: 1.1.0\n url_map_class = Map\n\n #: the test client that is used with when `test_client` is used.\n #:\n #: .. versionadded:: 0.7\n test_client_class: t.Optional[t.Type[\"FlaskClient\"]] = None\n\n #: The :class:`~click.testing.CliRunner` subclass, by default\n #: :class:`~flask.testing.FlaskCliRunner` that is used by\n #: :meth:`test_cli_runner`. Its ``__init__`` method should take a\n #: Flask app object as the first argument.\n #:\n #: .. versionadded:: 1.0\n test_cli_runner_class: t.Optional[t.Type[\"FlaskCliRunner\"]] = None\n\n #: the session interface to use. By default an instance of\n #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n #:\n #: .. versionadded:: 0.8\n session_interface = SecureCookieSessionInterface()\n\n def __init__(\n self,\n import_name: str,\n static_url_path: t.Optional[str] = None,\n static_folder: t.Optional[str] = \"static\",\n static_host: t.Optional[str] = None,\n host_matching: bool = False,\n subdomain_matching: bool = False,\n template_folder: t.Optional[str] = \"templates\",\n instance_path: t.Optional[str] = None,\n instance_relative_config: bool = False,\n root_path: t.Optional[str] = None,\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if instance_path is None:\n instance_path = self.auto_find_instance_path()\n elif not os.path.isabs(instance_path):\n raise ValueError(\n \"If an instance path is provided it must be absolute.\"\n \" A relative path was given instead.\"\n )\n\n #: Holds the path to the instance folder.\n #:\n #: .. versionadded:: 0.8\n self.instance_path = instance_path\n\n #: The configuration dictionary as :class:`Config`. This behaves\n #: exactly like a regular dictionary but supports additional methods\n #: to load a config from files.\n self.config = self.make_config(instance_relative_config)\n\n #: A list of functions that are called when :meth:`url_for` raises a\n #: :exc:`~werkzeug.routing.BuildError`. Each function registered here\n #: is called with `error`, `endpoint` and `values`. If a function\n #: returns ``None`` or raises a :exc:`BuildError` the next function is\n #: tried.\n #:\n #: .. versionadded:: 0.9\n self.url_build_error_handlers: t.List[\n t.Callable[[Exception, str, dict], str]\n ] = []\n\n #: A list of functions that will be called at the beginning of the\n #: first request to this instance. To register a function, use the\n #: :meth:`before_first_request` decorator.\n #:\n #: .. versionadded:: 0.8\n self.before_first_request_funcs: t.List[BeforeRequestCallable] = []\n\n #: A list of functions that are called when the application context\n #: is destroyed. Since the application context is also torn down\n #: if the request ends this is the place to store code that disconnects\n #: from databases.\n #:\n #: .. versionadded:: 0.9\n self.teardown_appcontext_funcs: t.List[TeardownCallable] = []\n\n #: A list of shell context processor functions that should be run\n #: when a shell context is created.\n #:\n #: .. versionadded:: 0.11\n self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = []\n\n #: Maps registered blueprint names to blueprint objects. The\n #: dict retains the order the blueprints were registered in.\n #: Blueprints can be registered multiple times, this dict does\n #: not track how often they were attached.\n #:\n #: .. versionadded:: 0.7\n self.blueprints: t.Dict[str, \"Blueprint\"] = {}\n\n #: a place where extensions can store application specific state. For\n #: example this is where an extension could store database engines and\n #: similar things.\n #:\n #: The key must match the name of the extension module. For example in\n #: case of a \"Flask-Foo\" extension in `flask_foo`, the key would be\n #: ``'foo'``.\n #:\n #: .. versionadded:: 0.7\n self.extensions: dict = {}\n\n #: The :class:`~werkzeug.routing.Map` for this instance. You can use\n #: this to change the routing converters after the class was created\n #: but before any routes are connected. Example::\n #:\n #: from werkzeug.routing import BaseConverter\n #:\n #: class ListConverter(BaseConverter):\n #: def to_python(self, value):\n #: return value.split(',')\n #: def to_url(self, values):\n #: return ','.join(super(ListConverter, self).to_url(value)\n #: for value in values)\n #:\n #: app = Flask(__name__)\n #: app.url_map.converters['list'] = ListConverter\n self.url_map = self.url_map_class()\n\n self.url_map.host_matching = host_matching\n self.subdomain_matching = subdomain_matching\n\n # tracks internally if the application already handled at least one\n # request.\n self._got_first_request = False\n self._before_request_lock = Lock()\n\n # Add a static route using the provided static_url_path, static_host,\n # and static_folder if there is a configured static_folder.\n # Note we do this without checking if static_folder exists.\n # For one, it might be created while the server is running (e.g. during\n # development). Also, Google App Engine stores static files somewhere\n if self.has_static_folder:\n assert (\n bool(static_host) == host_matching\n ), \"Invalid static_host/host_matching combination\"\n # Use a weakref to avoid creating a reference cycle between the app\n # and the view function (see #3761).\n self_ref = weakref.ref(self)\n self.add_url_rule(\n f\"{self.static_url_path}/\",\n endpoint=\"static\",\n host=static_host,\n view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950\n )\n\n # Set the name of the Click group in case someone wants to add\n # the app's commands to another CLI tool.\n self.cli.name = self.name\n\n def _is_setup_finished(self) -> bool:\n return self.debug and self._got_first_request\n\n @locked_cached_property\n def name(self) -> str: # type: ignore\n \"\"\"The name of the application. This is usually the import name\n with the difference that it's guessed from the run file if the\n import name is main. This name is used as a display name when\n Flask needs the name of the application. It can be set and overridden\n to change the value.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.import_name == \"__main__\":\n fn = getattr(sys.modules[\"__main__\"], \"__file__\", None)\n if fn is None:\n return \"__main__\"\n return os.path.splitext(os.path.basename(fn))[0]\n return self.import_name\n\n @property\n def propagate_exceptions(self) -> bool:\n \"\"\"Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration\n value in case it's set, otherwise a sensible default is returned.\n\n .. versionadded:: 0.7\n \"\"\"\n rv = self.config[\"PROPAGATE_EXCEPTIONS\"]\n if rv is not None:\n return rv\n return self.testing or self.debug\n\n @property\n def preserve_context_on_exception(self) -> bool:\n \"\"\"Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``\n configuration value in case it's set, otherwise a sensible default\n is returned.\n\n .. versionadded:: 0.7\n \"\"\"\n rv = self.config[\"PRESERVE_CONTEXT_ON_EXCEPTION\"]\n if rv is not None:\n return rv\n return self.debug\n\n @locked_cached_property\n def logger(self) -> logging.Logger:\n \"\"\"A standard Python :class:`~logging.Logger` for the app, with\n the same name as :attr:`name`.\n\n In debug mode, the logger's :attr:`~logging.Logger.level` will\n be set to :data:`~logging.DEBUG`.\n\n If there are no handlers configured, a default handler will be\n added. See :doc:`/logging` for more information.\n\n .. versionchanged:: 1.1.0\n The logger takes the same name as :attr:`name` rather than\n hard-coding ``\"flask.app\"``.\n\n .. versionchanged:: 1.0.0\n Behavior was simplified. The logger is always named\n ``\"flask.app\"``. The level is only set during configuration,\n it doesn't check ``app.debug`` each time. Only one format is\n used, not different ones depending on ``app.debug``. No\n handlers are removed, and a handler is only added if no\n handlers are already configured.\n\n .. versionadded:: 0.3\n \"\"\"\n return create_logger(self)\n\n @locked_cached_property\n def jinja_env(self) -> Environment:\n \"\"\"The Jinja environment used to load templates.\n\n The environment is created the first time this property is\n accessed. Changing :attr:`jinja_options` after that will have no\n effect.\n \"\"\"\n return self.create_jinja_environment()\n\n @property\n def got_first_request(self) -> bool:\n \"\"\"This attribute is set to ``True`` if the application started\n handling the first request.\n\n .. versionadded:: 0.8\n \"\"\"\n return self._got_first_request\n\n def make_config(self, instance_relative: bool = False) -> Config:\n \"\"\"Used to create the config attribute by the Flask constructor.\n The `instance_relative` parameter is passed in from the constructor\n of Flask (there named `instance_relative_config`) and indicates if\n the config should be relative to the instance path or the root path\n of the application.\n\n .. versionadded:: 0.8\n \"\"\"\n root_path = self.root_path\n if instance_relative:\n root_path = self.instance_path\n defaults = dict(self.default_config)\n defaults[\"ENV\"] = get_env()\n defaults[\"DEBUG\"] = get_debug_flag()\n return self.config_class(root_path, defaults)\n\n def auto_find_instance_path(self) -> str:\n \"\"\"Tries to locate the instance path if it was not provided to the\n constructor of the application class. It will basically calculate\n the path to a folder named ``instance`` next to your main file or\n the package.\n\n .. versionadded:: 0.8\n \"\"\"\n prefix, package_path = find_package(self.import_name)\n if prefix is None:\n return os.path.join(package_path, \"instance\")\n return os.path.join(prefix, \"var\", f\"{self.name}-instance\")\n\n def open_instance_resource(self, resource: str, mode: str = \"rb\") -> t.IO[t.AnyStr]:\n \"\"\"Opens a resource from the application's instance folder\n (:attr:`instance_path`). Otherwise works like\n :meth:`open_resource`. Instance resources can also be opened for\n writing.\n\n :param resource: the name of the resource. To access resources within\n subfolders use forward slashes as separator.\n :param mode: resource file opening mode, default is 'rb'.\n \"\"\"\n return open(os.path.join(self.instance_path, resource), mode)\n\n @property\n def templates_auto_reload(self) -> bool:\n \"\"\"Reload templates when they are changed. Used by\n :meth:`create_jinja_environment`.\n\n This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If\n not set, it will be enabled in debug mode.\n\n .. versionadded:: 1.0\n This property was added but the underlying config and behavior\n already existed.\n \"\"\"\n rv = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n return rv if rv is not None else self.debug\n\n @templates_auto_reload.setter\n def templates_auto_reload(self, value: bool) -> None:\n self.config[\"TEMPLATES_AUTO_RELOAD\"] = value\n\n def create_jinja_environment(self) -> Environment:\n \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n and the various Jinja-related methods of the app. Changing\n :attr:`jinja_options` after this will have no effect. Also adds\n Flask-related globals and filters to the environment.\n\n .. versionchanged:: 0.11\n ``Environment.auto_reload`` set in accordance with\n ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n .. versionadded:: 0.5\n \"\"\"\n options = dict(self.jinja_options)\n\n if \"autoescape\" not in options:\n options[\"autoescape\"] = self.select_jinja_autoescape\n\n if \"auto_reload\" not in options:\n options[\"auto_reload\"] = self.templates_auto_reload\n\n rv = self.jinja_environment(self, **options)\n rv.globals.update(\n url_for=url_for,\n get_flashed_messages=get_flashed_messages,\n config=self.config,\n # request, session and g are normally added with the\n # context processor for efficiency reasons but for imported\n # templates we also want the proxies in there.\n request=request,\n session=session,\n g=g,\n )\n rv.policies[\"json.dumps_function\"] = json.dumps\n return rv\n\n def create_global_jinja_loader(self) -> DispatchingJinjaLoader:\n \"\"\"Creates the loader for the Jinja2 environment. Can be used to\n override just the loader and keeping the rest unchanged. It's\n discouraged to override this function. Instead one should override\n the :meth:`jinja_loader` function instead.\n\n The global loader dispatches between the loaders of the application\n and the individual blueprints.\n\n .. versionadded:: 0.7\n \"\"\"\n return DispatchingJinjaLoader(self)\n\n def select_jinja_autoescape(self, filename: str) -> bool:\n \"\"\"Returns ``True`` if autoescaping should be active for the given\n template name. If no template name is given, returns `True`.\n\n .. versionadded:: 0.5\n \"\"\"\n if filename is None:\n return True\n return filename.endswith((\".html\", \".htm\", \".xml\", \".xhtml\"))\n\n def update_template_context(self, context: dict) -> None:\n \"\"\"Update the template context with some commonly used variables.\n This injects request, session, config and g into the template\n context as well as everything template context processors want\n to inject. Note that the as of Flask 0.6, the original values\n in the context will not be overridden if a context processor\n decides to return a value with the same key.\n\n :param context: the context as a dictionary that is updated in place\n to add extra variables.\n \"\"\"\n funcs: t.Iterable[\n TemplateContextProcessorCallable\n ] = self.template_context_processors[None]\n reqctx = _request_ctx_stack.top\n if reqctx is not None:\n for bp in self._request_blueprints():\n if bp in self.template_context_processors:\n funcs = chain(funcs, self.template_context_processors[bp])\n orig_ctx = context.copy()\n for func in funcs:\n context.update(func())\n # make sure the original values win. This makes it possible to\n # easier add new variables in context processors without breaking\n # existing views.\n context.update(orig_ctx)\n\n def make_shell_context(self) -> dict:\n \"\"\"Returns the shell context for an interactive shell for this\n application. This runs all the registered shell context\n processors.\n\n .. versionadded:: 0.11\n \"\"\"\n rv = {\"app\": self, \"g\": g}\n for processor in self.shell_context_processors:\n rv.update(processor())\n return rv\n\n #: What environment the app is running in. Flask and extensions may\n #: enable behaviors based on the environment, such as enabling debug\n #: mode. This maps to the :data:`ENV` config key. This is set by the\n #: :envvar:`FLASK_ENV` environment variable and may not behave as\n #: expected if set in code.\n #:\n #: **Do not enable development when deploying in production.**\n #:\n #: Default: ``'production'``\n env = ConfigAttribute(\"ENV\")\n\n @property\n def debug(self) -> bool:\n \"\"\"Whether debug mode is enabled. When using ``flask run`` to start\n the development server, an interactive debugger will be shown for\n unhandled exceptions, and the server will be reloaded when code\n changes. This maps to the :data:`DEBUG` config key. This is\n enabled when :attr:`env` is ``'development'`` and is overridden\n by the ``FLASK_DEBUG`` environment variable. It may not behave as\n expected if set in code.\n\n **Do not enable debug mode when deploying in production.**\n\n Default: ``True`` if :attr:`env` is ``'development'``, or\n ``False`` otherwise.\n \"\"\"\n return self.config[\"DEBUG\"]\n\n @debug.setter\n def debug(self, value: bool) -> None:\n self.config[\"DEBUG\"] = value\n self.jinja_env.auto_reload = self.templates_auto_reload\n\n def run(\n self,\n host: t.Optional[str] = None,\n port: t.Optional[int] = None,\n debug: t.Optional[bool] = None,\n load_dotenv: bool = True,\n **options: t.Any,\n ) -> None:\n \"\"\"Runs the application on a local development server.\n\n Do not use ``run()`` in a production setting. It is not intended to\n meet security and performance requirements for a production server.\n Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n If the :attr:`debug` flag is set the server will automatically reload\n for code changes and show a debugger in case an exception happened.\n\n If you want to run the application in debug mode, but disable the\n code execution on the interactive debugger, you can pass\n ``use_evalex=False`` as parameter. This will keep the debugger's\n traceback screen active, but disable code execution.\n\n It is not recommended to use this function for development with\n automatic reloading as this is badly supported. Instead you should\n be using the :command:`flask` command line script's ``run`` support.\n\n .. admonition:: Keep in Mind\n\n Flask will suppress any server error with a generic error page\n unless it is in debug mode. As such to enable just the\n interactive debugger without the code reloading, you have to\n invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n Setting ``use_debugger`` to ``True`` without being in debug mode\n won't catch any exceptions because there won't be any to\n catch.\n\n :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n have the server available externally as well. Defaults to\n ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n if present.\n :param port: the port of the webserver. Defaults to ``5000`` or the\n port defined in the ``SERVER_NAME`` config variable if present.\n :param debug: if given, enable or disable debug mode. See\n :attr:`debug`.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param options: the options to be forwarded to the underlying Werkzeug\n server. See :func:`werkzeug.serving.run_simple` for more\n information.\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment\n variables from :file:`.env` and :file:`.flaskenv` files.\n\n If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`\n environment variables will override :attr:`env` and\n :attr:`debug`.\n\n Threaded mode is enabled by default.\n\n .. versionchanged:: 0.10\n The default port is now picked from the ``SERVER_NAME``\n variable.\n \"\"\"\n # Change this into a no-op if the server is invoked from the\n # command line. Have a look at cli.py for more information.\n if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n from .debughelpers import explain_ignored_app_run\n\n explain_ignored_app_run()\n return\n\n if get_load_dotenv(load_dotenv):\n cli.load_dotenv()\n\n # if set, let env vars override previous values\n if \"FLASK_ENV\" in os.environ:\n self.env = get_env()\n self.debug = get_debug_flag()\n elif \"FLASK_DEBUG\" in os.environ:\n self.debug = get_debug_flag()\n\n # debug passed to method overrides all other sources\n if debug is not None:\n self.debug = bool(debug)\n\n server_name = self.config.get(\"SERVER_NAME\")\n sn_host = sn_port = None\n\n if server_name:\n sn_host, _, sn_port = server_name.partition(\":\")\n\n if not host:\n if sn_host:\n host = sn_host\n else:\n host = \"127.0.0.1\"\n\n if port or port == 0:\n port = int(port)\n elif sn_port:\n port = int(sn_port)\n else:\n port = 5000\n\n options.setdefault(\"use_reloader\", self.debug)\n options.setdefault(\"use_debugger\", self.debug)\n options.setdefault(\"threaded\", True)\n\n cli.show_server_banner(self.env, self.debug, self.name, False)\n\n from werkzeug.serving import run_simple\n\n try:\n run_simple(t.cast(str, host), port, self, **options)\n finally:\n # reset the first request information if the development server\n # reset normally. This makes it possible to restart the server\n # without reloader and that stuff from an interactive shell.\n self._got_first_request = False\n\n def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> \"FlaskClient\":\n \"\"\"Creates a test client for this application. For information\n about unit testing head over to :doc:`/testing`.\n\n Note that if you are testing for assertions or exceptions in your\n application code, you must set ``app.testing = True`` in order for the\n exceptions to propagate to the test client. Otherwise, the exception\n will be handled by the application (not visible to the test client) and\n the only indication of an AssertionError or other exception will be a\n 500 status code response to the test client. See the :attr:`testing`\n attribute. For example::\n\n app.testing = True\n client = app.test_client()\n\n The test client can be used in a ``with`` block to defer the closing down\n of the context until the end of the ``with`` block. This is useful if\n you want to access the context locals for testing::\n\n with app.test_client() as c:\n rv = c.get('/?vodka=42')\n assert request.args['vodka'] == '42'\n\n Additionally, you may pass optional keyword arguments that will then\n be passed to the application's :attr:`test_client_class` constructor.\n For example::\n\n from flask.testing import FlaskClient\n\n class CustomClient(FlaskClient):\n def __init__(self, *args, **kwargs):\n self._authentication = kwargs.pop(\"authentication\")\n super(CustomClient,self).__init__( *args, **kwargs)\n\n app.test_client_class = CustomClient\n client = app.test_client(authentication='Basic ....')\n\n See :class:`~flask.testing.FlaskClient` for more information.\n\n .. versionchanged:: 0.4\n added support for ``with`` block usage for the client.\n\n .. versionadded:: 0.7\n The `use_cookies` parameter was added as well as the ability\n to override the client to be used by setting the\n :attr:`test_client_class` attribute.\n\n .. versionchanged:: 0.11\n Added `**kwargs` to support passing additional keyword arguments to\n the constructor of :attr:`test_client_class`.\n \"\"\"\n cls = self.test_client_class\n if cls is None:\n from .testing import FlaskClient as cls # type: ignore\n return cls( # type: ignore\n self, self.response_class, use_cookies=use_cookies, **kwargs\n )\n\n def test_cli_runner(self, **kwargs: t.Any) -> \"FlaskCliRunner\":\n \"\"\"Create a CLI runner for testing CLI commands.\n See :ref:`testing-cli`.\n\n Returns an instance of :attr:`test_cli_runner_class`, by default\n :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n passed as the first argument.\n\n .. versionadded:: 1.0\n \"\"\"\n cls = self.test_cli_runner_class\n\n if cls is None:\n from .testing import FlaskCliRunner as cls # type: ignore\n\n return cls(self, **kwargs) # type: ignore\n\n @setupmethod\n def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on the application. Keyword\n arguments passed to this method will override the defaults set on the\n blueprint.\n\n Calls the blueprint's :meth:`~flask.Blueprint.register` method after\n recording the blueprint in the application's :attr:`blueprints`.\n\n :param blueprint: The blueprint to register.\n :param url_prefix: Blueprint routes will be prefixed with this.\n :param subdomain: Blueprint routes will match on this subdomain.\n :param url_defaults: Blueprint routes will use these default values for\n view arguments.\n :param options: Additional keyword arguments are passed to\n :class:`~flask.blueprints.BlueprintSetupState`. They can be\n accessed in :meth:`~flask.Blueprint.record` callbacks.\n\n .. versionadded:: 0.7\n \"\"\"\n blueprint.register(self, options)\n\n def iter_blueprints(self) -> t.ValuesView[\"Blueprint\"]:\n \"\"\"Iterates over all blueprints by the order they were registered.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.blueprints.values()\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n options[\"endpoint\"] = endpoint\n methods = options.pop(\"methods\", None)\n\n # if the methods are not given and the view_func object knows its\n # methods we can use that instead. If neither exists, we go with\n # a tuple of only ``GET`` as default.\n if methods is None:\n methods = getattr(view_func, \"methods\", None) or (\"GET\",)\n if isinstance(methods, str):\n raise TypeError(\n \"Allowed methods must be a list of strings, for\"\n ' example: @app.route(..., methods=[\"POST\"])'\n )\n methods = {item.upper() for item in methods}\n\n # Methods that should always be added\n required_methods = set(getattr(view_func, \"required_methods\", ()))\n\n # starting with Flask 0.8 the view_func object can disable and\n # force-enable the automatic options handling.\n if provide_automatic_options is None:\n provide_automatic_options = getattr(\n view_func, \"provide_automatic_options\", None\n )\n\n if provide_automatic_options is None:\n if \"OPTIONS\" not in methods:\n provide_automatic_options = True\n required_methods.add(\"OPTIONS\")\n else:\n provide_automatic_options = False\n\n # Add the required methods now.\n methods |= required_methods\n\n rule = self.url_rule_class(rule, methods=methods, **options)\n rule.provide_automatic_options = provide_automatic_options # type: ignore\n\n self.url_map.add(rule)\n if view_func is not None:\n old_func = self.view_functions.get(endpoint)\n if old_func is not None and old_func != view_func:\n raise AssertionError(\n \"View function mapping is overwriting an existing\"\n f\" endpoint function: {endpoint}\"\n )\n self.view_functions[endpoint] = view_func\n\n @setupmethod\n def template_filter(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register custom template filter.\n You can specify a name for the filter, otherwise the function\n name will be used. Example::\n\n @app.template_filter()\n def reverse(s):\n return s[::-1]\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:\n self.add_template_filter(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_filter(\n self, f: TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template filter. Works exactly like the\n :meth:`template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.filters[name or f.__name__] = f\n\n @setupmethod\n def template_test(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register custom template test.\n You can specify a name for the test, otherwise the function\n name will be used. Example::\n\n @app.template_test()\n def is_prime(n):\n if n == 2:\n return True\n for i in range(2, int(math.ceil(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateTestCallable) -> TemplateTestCallable:\n self.add_template_test(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_test(\n self, f: TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template test. Works exactly like the\n :meth:`template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.tests[name or f.__name__] = f\n\n @setupmethod\n def template_global(self, name: t.Optional[str] = None) -> t.Callable:\n \"\"\"A decorator that is used to register a custom template global function.\n You can specify a name for the global function, otherwise the function\n name will be used. Example::\n\n @app.template_global()\n def double(n):\n return 2 * n\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:\n self.add_template_global(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_global(\n self, f: TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template global function. Works exactly like the\n :meth:`template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.globals[name or f.__name__] = f\n\n @setupmethod\n def before_first_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:\n \"\"\"Registers a function to be run before the first request to this\n instance of the application.\n\n The function will be called without any arguments and its return\n value is ignored.\n\n .. versionadded:: 0.8\n \"\"\"\n self.before_first_request_funcs.append(f)\n return f\n\n @setupmethod\n def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:\n \"\"\"Registers a function to be called when the application context\n ends. These functions are typically also called when the request\n context is popped.\n\n Example::\n\n ctx = app.app_context()\n ctx.push()\n ...\n ctx.pop()\n\n When ``ctx.pop()`` is executed in the above example, the teardown\n functions are called just before the app context moves from the\n stack of active contexts. This becomes relevant if you are using\n such constructs in tests.\n\n Since a request context typically also manages an application\n context it would also be called when you pop a request context.\n\n When a teardown function was called because of an unhandled exception\n it will be passed an error object. If an :meth:`errorhandler` is\n registered, it will handle the exception and the teardown will not\n receive it.\n\n The return values of teardown functions are ignored.\n\n .. versionadded:: 0.9\n \"\"\"\n self.teardown_appcontext_funcs.append(f)\n return f\n\n @setupmethod\n def shell_context_processor(self, f: t.Callable) -> t.Callable:\n \"\"\"Registers a shell context processor function.\n\n .. versionadded:: 0.11\n \"\"\"\n self.shell_context_processors.append(f)\n return f\n\n def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:\n \"\"\"Return a registered error handler for an exception in this order:\n blueprint handler for a specific code, app handler for a specific code,\n blueprint handler for an exception class, app handler for an exception\n class, or ``None`` if a suitable handler is not found.\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(type(e))\n\n for c in [code, None]:\n for name in chain(self._request_blueprints(), [None]):\n handler_map = self.error_handler_spec[name][c]\n\n if not handler_map:\n continue\n\n for cls in exc_class.__mro__:\n handler = handler_map.get(cls)\n\n if handler is not None:\n return handler\n return None\n\n def handle_http_exception(\n self, e: HTTPException\n ) -> t.Union[HTTPException, ResponseReturnValue]:\n \"\"\"Handles an HTTP exception. By default this will invoke the\n registered error handlers and fall back to returning the\n exception as response.\n\n .. versionchanged:: 1.0.3\n ``RoutingException``, used internally for actions such as\n slash redirects during routing, is not passed to error\n handlers.\n\n .. versionchanged:: 1.0\n Exceptions are looked up by code *and* by MRO, so\n ``HTTPExcpetion`` subclasses can be handled with a catch-all\n handler for the base ``HTTPException``.\n\n .. versionadded:: 0.3\n \"\"\"\n # Proxy exceptions don't have error codes. We want to always return\n # those unchanged as errors\n if e.code is None:\n return e\n\n # RoutingExceptions are used internally to trigger routing\n # actions, such as slash redirects raising RequestRedirect. They\n # are not raised or handled in user code.\n if isinstance(e, RoutingException):\n return e\n\n handler = self._find_error_handler(e)\n if handler is None:\n return e\n return self.ensure_sync(handler)(e)\n\n def trap_http_exception(self, e: Exception) -> bool:\n \"\"\"Checks if an HTTP exception should be trapped or not. By default\n this will return ``False`` for all exceptions except for a bad request\n key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It\n also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.\n\n This is called for all HTTP exceptions raised by a view function.\n If it returns ``True`` for any exception the error handler for this\n exception is not called and it shows up as regular exception in the\n traceback. This is helpful for debugging implicitly raised HTTP\n exceptions.\n\n .. versionchanged:: 1.0\n Bad request errors are not trapped by default in debug mode.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.config[\"TRAP_HTTP_EXCEPTIONS\"]:\n return True\n\n trap_bad_request = self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n\n # if unset, trap key errors in debug mode\n if (\n trap_bad_request is None\n and self.debug\n and isinstance(e, BadRequestKeyError)\n ):\n return True\n\n if trap_bad_request:\n return isinstance(e, BadRequest)\n\n return False\n\n def handle_user_exception(\n self, e: Exception\n ) -> t.Union[HTTPException, ResponseReturnValue]:\n \"\"\"This method is called whenever an exception occurs that\n should be handled. A special case is :class:`~werkzeug\n .exceptions.HTTPException` which is forwarded to the\n :meth:`handle_http_exception` method. This function will either\n return a response value or reraise the exception with the same\n traceback.\n\n .. versionchanged:: 1.0\n Key errors raised from request data like ``form`` show the\n bad key in debug mode rather than a generic bad request\n message.\n\n .. versionadded:: 0.7\n \"\"\"\n if isinstance(e, BadRequestKeyError) and (\n self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n ):\n e.show_exception = True\n\n if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n return self.handle_http_exception(e)\n\n handler = self._find_error_handler(e)\n\n if handler is None:\n raise\n\n return self.ensure_sync(handler)(e)\n\n def handle_exception(self, e: Exception) -> Response:\n \"\"\"Handle an exception that did not have an error handler\n associated with it, or that was raised from an error handler.\n This always causes a 500 ``InternalServerError``.\n\n Always sends the :data:`got_request_exception` signal.\n\n If :attr:`propagate_exceptions` is ``True``, such as in debug\n mode, the error will be re-raised so that the debugger can\n display it. Otherwise, the original exception is logged, and\n an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n If an error handler is registered for ``InternalServerError`` or\n ``500``, it will be used. For consistency, the handler will\n always receive the ``InternalServerError``. The original\n unhandled exception is available as ``e.original_exception``.\n\n .. versionchanged:: 1.1.0\n Always passes the ``InternalServerError`` instance to the\n handler, setting ``original_exception`` to the unhandled\n error.\n\n .. versionchanged:: 1.1.0\n ``after_request`` functions and other finalization is done\n even for the default 500 response when there is no handler.\n\n .. versionadded:: 0.3\n \"\"\"\n exc_info = sys.exc_info()\n got_request_exception.send(self, exception=e)\n\n if self.propagate_exceptions:\n # Re-raise if called with an active exception, otherwise\n # raise the passed in exception.\n if exc_info[1] is e:\n raise\n\n raise e\n\n self.log_exception(exc_info)\n server_error: t.Union[InternalServerError, ResponseReturnValue]\n server_error = InternalServerError(original_exception=e)\n handler = self._find_error_handler(server_error)\n\n if handler is not None:\n server_error = self.ensure_sync(handler)(server_error)\n\n return self.finalize_request(server_error, from_error_handler=True)\n\n def log_exception(\n self,\n exc_info: t.Union[\n t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]\n ],\n ) -> None:\n \"\"\"Logs an exception. This is called by :meth:`handle_exception`\n if debugging is disabled and right before the handler is called.\n The default implementation logs the exception as error on the\n :attr:`logger`.\n\n .. versionadded:: 0.8\n \"\"\"\n self.logger.error(\n f\"Exception on {request.path} [{request.method}]\", exc_info=exc_info\n )\n\n def raise_routing_exception(self, request: Request) -> \"te.NoReturn\":\n \"\"\"Exceptions that are recording during routing are reraised with\n this method. During debug we are not reraising redirect requests\n for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising\n a different error instead to help debug situations.\n\n :internal:\n \"\"\"\n if (\n not self.debug\n or not isinstance(request.routing_exception, RequestRedirect)\n or request.method in (\"GET\", \"HEAD\", \"OPTIONS\")\n ):\n raise request.routing_exception # type: ignore\n\n from .debughelpers import FormDataRoutingRedirect\n\n raise FormDataRoutingRedirect(request)\n\n def dispatch_request(self) -> ResponseReturnValue:\n \"\"\"Does the request dispatching. Matches the URL and returns the\n return value of the view or error handler. This does not have to\n be a response object. In order to convert the return value to a\n proper response object, call :func:`make_response`.\n\n .. versionchanged:: 0.7\n This no longer does the exception handling, this code was\n moved to the new :meth:`full_dispatch_request`.\n \"\"\"\n req = _request_ctx_stack.top.request\n if req.routing_exception is not None:\n self.raise_routing_exception(req)\n rule = req.url_rule\n # if we provide automatic options for this URL and the\n # request came with the OPTIONS method, reply automatically\n if (\n getattr(rule, \"provide_automatic_options\", False)\n and req.method == \"OPTIONS\"\n ):\n return self.make_default_options_response()\n # otherwise dispatch to the handler for that endpoint\n return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n\n def full_dispatch_request(self) -> Response:\n \"\"\"Dispatches the request and on top of that performs request\n pre and postprocessing as well as HTTP exception catching and\n error handling.\n\n .. versionadded:: 0.7\n \"\"\"\n self.try_trigger_before_first_request_functions()\n try:\n request_started.send(self)\n rv = self.preprocess_request()\n if rv is None:\n rv = self.dispatch_request()\n except Exception as e:\n rv = self.handle_user_exception(e)\n return self.finalize_request(rv)\n\n def finalize_request(\n self,\n rv: t.Union[ResponseReturnValue, HTTPException],\n from_error_handler: bool = False,\n ) -> Response:\n \"\"\"Given the return value from a view function this finalizes\n the request by converting it into a response and invoking the\n postprocessing functions. This is invoked for both normal\n request dispatching as well as error handlers.\n\n Because this means that it might be called as a result of a\n failure a special safe mode is available which can be enabled\n with the `from_error_handler` flag. If enabled, failures in\n response processing will be logged and otherwise ignored.\n\n :internal:\n \"\"\"\n response = self.make_response(rv)\n try:\n response = self.process_response(response)\n request_finished.send(self, response=response)\n except Exception:\n if not from_error_handler:\n raise\n self.logger.exception(\n \"Request finalizing failed with an error while handling an error\"\n )\n return response\n\n def try_trigger_before_first_request_functions(self) -> None:\n \"\"\"Called before each request and will ensure that it triggers\n the :attr:`before_first_request_funcs` and only exactly once per\n application instance (which means process usually).\n\n :internal:\n \"\"\"\n if self._got_first_request:\n return\n with self._before_request_lock:\n if self._got_first_request:\n return\n for func in self.before_first_request_funcs:\n self.ensure_sync(func)()\n self._got_first_request = True\n\n def make_default_options_response(self) -> Response:\n \"\"\"This method is called to create the default ``OPTIONS`` response.\n This can be changed through subclassing to change the default\n behavior of ``OPTIONS`` responses.\n\n .. versionadded:: 0.7\n \"\"\"\n adapter = _request_ctx_stack.top.url_adapter\n methods = adapter.allowed_methods()\n rv = self.response_class()\n rv.allow.update(methods)\n return rv\n\n def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:\n \"\"\"This is called to figure out if an error should be ignored\n or not as far as the teardown system is concerned. If this\n function returns ``True`` then the teardown handlers will not be\n passed the error.\n\n .. versionadded:: 0.10\n \"\"\"\n return False\n\n def ensure_sync(self, func: t.Callable) -> t.Callable:\n \"\"\"Ensure that the function is synchronous for WSGI workers.\n Plain ``def`` functions are returned as-is. ``async def``\n functions are wrapped to run and wait for the response.\n\n Override this method to change how the app runs async views.\n\n .. versionadded:: 2.0\n \"\"\"\n if iscoroutinefunction(func):\n return self.async_to_sync(func)\n\n return func\n\n def async_to_sync(\n self, func: t.Callable[..., t.Coroutine]\n ) -> t.Callable[..., t.Any]:\n \"\"\"Return a sync function that will run the coroutine function.\n\n .. code-block:: python\n\n result = app.async_to_sync(func)(*args, **kwargs)\n\n Override this method to change how the app converts async code\n to be synchronously callable.\n\n .. versionadded:: 2.0\n \"\"\"\n try:\n from asgiref.sync import async_to_sync as asgiref_async_to_sync\n except ImportError:\n raise RuntimeError(\n \"Install Flask with the 'async' extra in order to use async views.\"\n )\n\n # Check that Werkzeug isn't using its fallback ContextVar class.\n if ContextVar.__module__ == \"werkzeug.local\":\n raise RuntimeError(\n \"Async cannot be used with this combination of Python \"\n \"and Greenlet versions.\"\n )\n\n return asgiref_async_to_sync(func)\n\n def make_response(self, rv: ResponseReturnValue) -> Response:\n \"\"\"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n A dictionary that will be jsonify'd before being returned.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n ``headers`` is a dictionary or a list of ``(key, value)``\n tuples. If ``body`` is a :attr:`response_class` instance,\n ``status`` overwrites the exiting value and ``headers`` are\n extended.\n\n :attr:`response_class`\n The object is returned unchanged.\n\n other :class:`~werkzeug.wrappers.Response` class\n The object is coerced to :attr:`response_class`.\n\n :func:`callable`\n The function is called as a WSGI application. The result is\n used to create a response object.\n\n .. versionchanged:: 0.9\n Previously a tuple was interpreted as the arguments for the\n response object.\n \"\"\"\n\n status = headers = None\n\n # unpack tuple returns\n if isinstance(rv, tuple):\n len_rv = len(rv)\n\n # a 3-tuple is unpacked directly\n if len_rv == 3:\n rv, status, headers = rv\n # decide if a 2-tuple has status or headers\n elif len_rv == 2:\n if isinstance(rv[1], (Headers, dict, tuple, list)):\n rv, headers = rv\n else:\n rv, status = rv\n # other sized tuples are not allowed\n else:\n raise TypeError(\n \"The view function did not return a valid response tuple.\"\n \" The tuple must have the form (body, status, headers),\"\n \" (body, status), or (body, headers).\"\n )\n\n # the body must not be None\n if rv is None:\n raise TypeError(\n f\"The view function for {request.endpoint!r} did not\"\n \" return a valid response. The function either returned\"\n \" None or ended without a return statement.\"\n )\n\n # make sure the body is an instance of the response class\n if not isinstance(rv, self.response_class):\n if isinstance(rv, (str, bytes, bytearray)):\n # let the response class set the status and headers instead of\n # waiting to do it manually, so that the class can handle any\n # special logic\n rv = self.response_class(rv, status=status, headers=headers)\n status = headers = None\n elif isinstance(rv, dict):\n rv = jsonify(rv)\n elif isinstance(rv, BaseResponse) or callable(rv):\n # evaluate a WSGI callable, or coerce a different response\n # class to the correct type\n try:\n rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B950\n except TypeError as e:\n raise TypeError(\n f\"{e}\\nThe view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, tuple, Response instance, or WSGI\"\n f\" callable, but it was a {type(rv).__name__}.\"\n ).with_traceback(sys.exc_info()[2])\n else:\n raise TypeError(\n \"The view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, tuple, Response instance, or WSGI\"\n f\" callable, but it was a {type(rv).__name__}.\"\n )\n\n rv = t.cast(Response, rv)\n # prefer the status if it was provided\n if status is not None:\n if isinstance(status, (str, bytes, bytearray)):\n rv.status = status # type: ignore\n else:\n rv.status_code = status\n\n # extend existing headers with provided headers\n if headers:\n rv.headers.update(headers)\n\n return rv\n\n def create_url_adapter(\n self, request: t.Optional[Request]\n ) -> t.Optional[MapAdapter]:\n \"\"\"Creates a URL adapter for the given request. The URL adapter\n is created at a point where the request context is not yet set\n up so the request is passed explicitly.\n\n .. versionadded:: 0.6\n\n .. versionchanged:: 0.9\n This can now also be called without a request object when the\n URL adapter is created for the application context.\n\n .. versionchanged:: 1.0\n :data:`SERVER_NAME` no longer implicitly enables subdomain\n matching. Use :attr:`subdomain_matching` instead.\n \"\"\"\n if request is not None:\n # If subdomain matching is disabled (the default), use the\n # default subdomain in all cases. This should be the default\n # in Werkzeug but it currently does not have that feature.\n if not self.subdomain_matching:\n subdomain = self.url_map.default_subdomain or None\n else:\n subdomain = None\n\n return self.url_map.bind_to_environ(\n request.environ,\n server_name=self.config[\"SERVER_NAME\"],\n subdomain=subdomain,\n )\n # We need at the very least the server name to be set for this\n # to work.\n if self.config[\"SERVER_NAME\"] is not None:\n return self.url_map.bind(\n self.config[\"SERVER_NAME\"],\n script_name=self.config[\"APPLICATION_ROOT\"],\n url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n )\n\n return None\n\n def inject_url_defaults(self, endpoint: str, values: dict) -> None:\n \"\"\"Injects the URL defaults for the given endpoint directly into\n the values dictionary passed. This is used internally and\n automatically called on URL building.\n\n .. versionadded:: 0.7\n \"\"\"\n funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]\n if \".\" in endpoint:\n bp = endpoint.rsplit(\".\", 1)[0]\n funcs = chain(funcs, self.url_default_functions[bp])\n for func in funcs:\n func(endpoint, values)\n\n def handle_url_build_error(\n self, error: Exception, endpoint: str, values: dict\n ) -> str:\n \"\"\"Handle :class:`~werkzeug.routing.BuildError` on\n :meth:`url_for`.\n \"\"\"\n for handler in self.url_build_error_handlers:\n try:\n rv = handler(error, endpoint, values)\n except BuildError as e:\n # make error available outside except block\n error = e\n else:\n if rv is not None:\n return rv\n\n # Re-raise if called with an active exception, otherwise raise\n # the passed in exception.\n if error is sys.exc_info()[1]:\n raise\n\n raise error\n\n def preprocess_request(self) -> t.Optional[ResponseReturnValue]:\n \"\"\"Called before the request is dispatched. Calls\n :attr:`url_value_preprocessors` registered with the app and the\n current blueprint (if any). Then calls :attr:`before_request_funcs`\n registered with the app and the blueprint.\n\n If any :meth:`before_request` handler returns a non-None value, the\n value is handled as if it was the return value from the view, and\n further request handling is stopped.\n \"\"\"\n\n funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[\n None\n ]\n for bp in self._request_blueprints():\n if bp in self.url_value_preprocessors:\n funcs = chain(funcs, self.url_value_preprocessors[bp])\n for func in funcs:\n func(request.endpoint, request.view_args)\n\n funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]\n for bp in self._request_blueprints():\n if bp in self.before_request_funcs:\n funcs = chain(funcs, self.before_request_funcs[bp])\n for func in funcs:\n rv = self.ensure_sync(func)()\n if rv is not None:\n return rv\n\n return None\n\n def process_response(self, response: Response) -> Response:\n \"\"\"Can be overridden in order to modify the response object\n before it's sent to the WSGI server. By default this will\n call all the :meth:`after_request` decorated functions.\n\n .. versionchanged:: 0.5\n As of Flask 0.5 the functions registered for after request\n execution are called in reverse order of registration.\n\n :param response: a :attr:`response_class` object.\n :return: a new response object or the same, has to be an\n instance of :attr:`response_class`.\n \"\"\"\n ctx = _request_ctx_stack.top\n funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions\n for bp in self._request_blueprints():\n if bp in self.after_request_funcs:\n funcs = chain(funcs, reversed(self.after_request_funcs[bp]))\n if None in self.after_request_funcs:\n funcs = chain(funcs, reversed(self.after_request_funcs[None]))\n for handler in funcs:\n response = self.ensure_sync(handler)(response)\n if not self.session_interface.is_null_session(ctx.session):\n self.session_interface.save_session(self, ctx.session, response)\n return response\n\n def do_teardown_request(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called after the request is dispatched and the response is\n returned, right before the request context is popped.\n\n This calls all functions decorated with\n :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`\n if a blueprint handled the request. Finally, the\n :data:`request_tearing_down` signal is sent.\n\n This is called by\n :meth:`RequestContext.pop() `,\n which may be delayed during testing to maintain access to\n resources.\n\n :param exc: An unhandled exception raised while dispatching the\n request. Detected from the current exception information if\n not passed. Passed to each teardown function.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n funcs: t.Iterable[TeardownCallable] = reversed(\n self.teardown_request_funcs[None]\n )\n for bp in self._request_blueprints():\n if bp in self.teardown_request_funcs:\n funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))\n for func in funcs:\n self.ensure_sync(func)(exc)\n request_tearing_down.send(self, exc=exc)\n\n def do_teardown_appcontext(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called right before the application context is popped.\n\n When handling a request, the application context is popped\n after the request context. See :meth:`do_teardown_request`.\n\n This calls all functions decorated with\n :meth:`teardown_appcontext`. Then the\n :data:`appcontext_tearing_down` signal is sent.\n\n This is called by\n :meth:`AppContext.pop() `.\n\n .. versionadded:: 0.9\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n for func in reversed(self.teardown_appcontext_funcs):\n self.ensure_sync(func)(exc)\n appcontext_tearing_down.send(self, exc=exc)\n\n def app_context(self) -> AppContext:\n \"\"\"Create an :class:`~flask.ctx.AppContext`. Use as a ``with``\n block to push the context, which will make :data:`current_app`\n point at this application.\n\n An application context is automatically pushed by\n :meth:`RequestContext.push() `\n when handling a request, and when running a CLI command. Use\n this to manually create a context outside of these situations.\n\n ::\n\n with app.app_context():\n init_db()\n\n See :doc:`/appcontext`.\n\n .. versionadded:: 0.9\n \"\"\"\n return AppContext(self)\n\n def request_context(self, environ: dict) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` representing a\n WSGI environment. Use a ``with`` block to push the context,\n which will make :data:`request` point at this request.\n\n See :doc:`/reqcontext`.\n\n Typically you should not call this from your own code. A request\n context is automatically pushed by the :meth:`wsgi_app` when\n handling a request. Use :meth:`test_request_context` to create\n an environment and context instead of this method.\n\n :param environ: a WSGI environment\n \"\"\"\n return RequestContext(self, environ)\n\n def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` for a WSGI\n environment created from the given values. This is mostly useful\n during testing, where you may want to run a function that uses\n request data without dispatching a full request.\n\n See :doc:`/reqcontext`.\n\n Use a ``with`` block to push the context, which will make\n :data:`request` point at the request for the created\n environment. ::\n\n with test_request_context(...):\n generate_report()\n\n When using the shell, it may be easier to push and pop the\n context manually to avoid indentation. ::\n\n ctx = app.test_request_context(...)\n ctx.push()\n ...\n ctx.pop()\n\n Takes the same arguments as Werkzeug's\n :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n the application. See the linked Werkzeug docs for most of the\n available arguments. Flask-specific behavior is listed here.\n\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to\n :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param data: The request body, either as a string or a dict of\n form keys and values.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n from .testing import EnvironBuilder\n\n builder = EnvironBuilder(self, *args, **kwargs)\n\n try:\n return self.request_context(builder.get_environ())\n finally:\n builder.close()\n\n def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The actual WSGI application. This is not implemented in\n :meth:`__call__` so that middlewares can be applied without\n losing a reference to the app object. Instead of doing this::\n\n app = MyMiddleware(app)\n\n It's a better idea to do this instead::\n\n app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n Then you still have the original application object around and\n can continue to call methods on it.\n\n .. versionchanged:: 0.7\n Teardown events for the request and app contexts are called\n even if an unhandled error occurs. Other events may not be\n called depending on when an error occurs during dispatch.\n See :ref:`callbacks-and-errors`.\n\n :param environ: A WSGI environment.\n :param start_response: A callable accepting a status code,\n a list of headers, and an optional exception context to\n start the response.\n \"\"\"\n ctx = self.request_context(environ)\n error: t.Optional[BaseException] = None\n try:\n try:\n ctx.push()\n response = self.full_dispatch_request()\n except Exception as e:\n error = e\n response = self.handle_exception(e)\n except: # noqa: B001\n error = sys.exc_info()[1]\n raise\n return response(environ, start_response)\n finally:\n if self.should_ignore_error(error):\n error = None\n ctx.auto_pop(error)\n\n def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The WSGI server calls the Flask application object as the\n WSGI application. This calls :meth:`wsgi_app`, which can be\n wrapped to apply middleware.\n \"\"\"\n return self.wsgi_app(environ, start_response)\n\n def _request_blueprints(self) -> t.Iterable[str]:\n if _request_ctx_stack.top.request.blueprint is None:\n return []\n else:\n return reversed(_request_ctx_stack.top.request.blueprint.split(\".\"))\n"},{"col":0,"comment":"Check whether calling a function raised a ``TypeError`` because\n the call failed or because something in the factory raised the\n error.\n\n :param f: The function that was called.\n :return: ``True`` if the call failed.\n ","endLoc":145,"header":"def _called_with_wrong_args(f)","id":875,"name":"_called_with_wrong_args","nodeType":"Function","startLoc":122,"text":"def _called_with_wrong_args(f):\n \"\"\"Check whether calling a function raised a ``TypeError`` because\n the call failed or because something in the factory raised the\n error.\n\n :param f: The function that was called.\n :return: ``True`` if the call failed.\n \"\"\"\n tb = sys.exc_info()[2]\n\n try:\n while tb is not None:\n if tb.tb_frame.f_code is f.__code__:\n # In the function, it was called successfully.\n return False\n\n tb = tb.tb_next\n\n # Didn't reach the function.\n return True\n finally:\n # Delete tb to break a circular reference.\n # https://docs.python.org/2/library/sys.html#sys.exc_info\n del tb"},{"col":0,"comment":"A tmpdir added to sys.path.","endLoc":135,"header":"@pytest.fixture\ndef modules_tmpdir(tmpdir, monkeypatch)","id":876,"name":"modules_tmpdir","nodeType":"Function","startLoc":130,"text":"@pytest.fixture\ndef modules_tmpdir(tmpdir, monkeypatch):\n \"\"\"A tmpdir added to sys.path.\"\"\"\n rv = tmpdir.mkdir(\"modules_tmpdir\")\n monkeypatch.syspath_prepend(str(rv))\n return rv"},{"col":0,"comment":"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n ","endLoc":220,"header":"def find_app_by_string(script_info, module, app_name)","id":877,"name":"find_app_by_string","nodeType":"Function","startLoc":148,"text":"def find_app_by_string(script_info, module, app_name):\n \"\"\"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n \"\"\"\n from . import Flask\n\n # Parse app_name as a single expression to determine if it's a valid\n # attribute name or function call.\n try:\n expr = ast.parse(app_name.strip(), mode=\"eval\").body\n except SyntaxError:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n if isinstance(expr, ast.Name):\n name = expr.id\n args = kwargs = None\n elif isinstance(expr, ast.Call):\n # Ensure the function name is an attribute name only.\n if not isinstance(expr.func, ast.Name):\n raise NoAppException(\n f\"Function reference must be a simple name: {app_name!r}.\"\n )\n\n name = expr.func.id\n\n # Parse the positional and keyword arguments as literals.\n try:\n args = [ast.literal_eval(arg) for arg in expr.args]\n kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}\n except ValueError:\n # literal_eval gives cryptic error messages, show a generic\n # message with the full expression instead.\n raise NoAppException(\n f\"Failed to parse arguments as literal values: {app_name!r}.\"\n )\n else:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n try:\n attr = getattr(module, name)\n except AttributeError:\n raise NoAppException(\n f\"Failed to find attribute {name!r} in {module.__name__!r}.\"\n )\n\n # If the attribute is a function, call it with any args and kwargs\n # to get the real application.\n if inspect.isfunction(attr):\n try:\n app = call_factory(script_info, attr, args, kwargs)\n except TypeError:\n if not _called_with_wrong_args(attr):\n raise\n\n raise NoAppException(\n f\"The factory {app_name!r} in module\"\n f\" {module.__name__!r} could not be called with the\"\n \" specified arguments.\"\n )\n else:\n app = attr\n\n if isinstance(app, Flask):\n return app\n\n raise NoAppException(\n \"A valid Flask application was not obtained from\"\n f\" '{module.__name__}:{app_name}'.\"\n )"},{"col":0,"comment":"null","endLoc":141,"header":"@pytest.fixture\ndef modules_tmpdir_prefix(modules_tmpdir, monkeypatch)","id":878,"name":"modules_tmpdir_prefix","nodeType":"Function","startLoc":138,"text":"@pytest.fixture\ndef modules_tmpdir_prefix(modules_tmpdir, monkeypatch):\n monkeypatch.setattr(sys, \"prefix\", str(modules_tmpdir))\n return modules_tmpdir"},{"fileName":"globals.py","filePath":"src/flask","id":879,"nodeType":"File","text":"import typing as t\nfrom functools import partial\n\nfrom werkzeug.local import LocalProxy\nfrom werkzeug.local import LocalStack\n\nif t.TYPE_CHECKING:\n from .app import Flask\n from .ctx import _AppCtxGlobals\n from .sessions import SessionMixin\n from .wrappers import Request\n\n_request_ctx_err_msg = \"\"\"\\\nWorking outside of request context.\n\nThis typically means that you attempted to use functionality that needed\nan active HTTP request. Consult the documentation on testing for\ninformation about how to avoid this problem.\\\n\"\"\"\n_app_ctx_err_msg = \"\"\"\\\nWorking outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in some way. To solve\nthis, set up an application context with app.app_context(). See the\ndocumentation for more information.\\\n\"\"\"\n\n\ndef _lookup_req_object(name):\n top = _request_ctx_stack.top\n if top is None:\n raise RuntimeError(_request_ctx_err_msg)\n return getattr(top, name)\n\n\ndef _lookup_app_object(name):\n top = _app_ctx_stack.top\n if top is None:\n raise RuntimeError(_app_ctx_err_msg)\n return getattr(top, name)\n\n\ndef _find_app():\n top = _app_ctx_stack.top\n if top is None:\n raise RuntimeError(_app_ctx_err_msg)\n return top.app\n\n\n# context locals\n_request_ctx_stack = LocalStack()\n_app_ctx_stack = LocalStack()\ncurrent_app: \"Flask\" = LocalProxy(_find_app) # type: ignore\nrequest: \"Request\" = LocalProxy(partial(_lookup_req_object, \"request\")) # type: ignore\nsession: \"SessionMixin\" = LocalProxy( # type: ignore\n partial(_lookup_req_object, \"session\")\n)\ng: \"_AppCtxGlobals\" = LocalProxy(partial(_lookup_app_object, \"g\")) # type: ignore\n"},{"className":"FlaskClient","col":0,"comment":"Works like a regular Werkzeug test client but has some knowledge about\n how Flask works to defer the cleanup of the request context stack to the\n end of a ``with`` body when used in a ``with`` statement. For general\n information about how to use this class refer to\n :class:`werkzeug.test.Client`.\n\n .. versionchanged:: 0.12\n `app.test_client()` includes preset default environment, which can be\n set after instantiation of the `app.test_client()` object in\n `client.environ_base`.\n\n Basic usage is outlined in the :doc:`/testing` chapter.\n ","endLoc":244,"id":880,"nodeType":"Class","startLoc":94,"text":"class FlaskClient(Client):\n \"\"\"Works like a regular Werkzeug test client but has some knowledge about\n how Flask works to defer the cleanup of the request context stack to the\n end of a ``with`` body when used in a ``with`` statement. For general\n information about how to use this class refer to\n :class:`werkzeug.test.Client`.\n\n .. versionchanged:: 0.12\n `app.test_client()` includes preset default environment, which can be\n set after instantiation of the `app.test_client()` object in\n `client.environ_base`.\n\n Basic usage is outlined in the :doc:`/testing` chapter.\n \"\"\"\n\n application: \"Flask\"\n preserve_context = False\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.environ_base = {\n \"REMOTE_ADDR\": \"127.0.0.1\",\n \"HTTP_USER_AGENT\": f\"werkzeug/{werkzeug.__version__}\",\n }\n\n @contextmanager\n def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Generator[SessionMixin, None, None]:\n \"\"\"When used in combination with a ``with`` statement this opens a\n session transaction. This can be used to modify the session that\n the test client uses. Once the ``with`` block is left the session is\n stored back.\n\n ::\n\n with client.session_transaction() as session:\n session['value'] = 42\n\n Internally this is implemented by going through a temporary test\n request context and since session handling could depend on\n request variables this function accepts the same arguments as\n :meth:`~flask.Flask.test_request_context` which are directly\n passed through.\n \"\"\"\n if self.cookie_jar is None:\n raise RuntimeError(\n \"Session transactions only make sense with cookies enabled.\"\n )\n app = self.application\n environ_overrides = kwargs.setdefault(\"environ_overrides\", {})\n self.cookie_jar.inject_wsgi(environ_overrides)\n outer_reqctx = _request_ctx_stack.top\n with app.test_request_context(*args, **kwargs) as c:\n session_interface = app.session_interface\n sess = session_interface.open_session(app, c.request)\n if sess is None:\n raise RuntimeError(\n \"Session backend did not open a session. Check the configuration\"\n )\n\n # Since we have to open a new request context for the session\n # handling we want to make sure that we hide out own context\n # from the caller. By pushing the original request context\n # (or None) on top of this and popping it we get exactly that\n # behavior. It's important to not use the push and pop\n # methods of the actual request context object since that would\n # mean that cleanup handlers are called\n _request_ctx_stack.push(outer_reqctx)\n try:\n yield sess\n finally:\n _request_ctx_stack.pop()\n\n resp = app.response_class()\n if not session_interface.is_null_session(sess):\n session_interface.save_session(app, sess, resp)\n headers = resp.get_wsgi_headers(c.request.environ)\n self.cookie_jar.extract_wsgi(c.request.environ, headers)\n\n def open( # type: ignore\n self,\n *args: t.Any,\n as_tuple: bool = False,\n buffered: bool = False,\n follow_redirects: bool = False,\n **kwargs: t.Any,\n ) -> \"Response\":\n # Same logic as super.open, but apply environ_base and preserve_context.\n request = None\n\n def copy_environ(other):\n return {\n **self.environ_base,\n **other,\n \"flask._preserve_context\": self.preserve_context,\n }\n\n if not kwargs and len(args) == 1:\n arg = args[0]\n\n if isinstance(arg, werkzeug.test.EnvironBuilder):\n builder = copy(arg)\n builder.environ_base = copy_environ(builder.environ_base or {})\n request = builder.get_request()\n elif isinstance(arg, dict):\n request = EnvironBuilder.from_environ(\n arg, app=self.application, environ_base=copy_environ({})\n ).get_request()\n elif isinstance(arg, BaseRequest):\n request = copy(arg)\n request.environ = copy_environ(request.environ)\n\n if request is None:\n kwargs[\"environ_base\"] = copy_environ(kwargs.get(\"environ_base\", {}))\n builder = EnvironBuilder(self.application, *args, **kwargs)\n\n try:\n request = builder.get_request()\n finally:\n builder.close()\n\n return super().open( # type: ignore\n request,\n as_tuple=as_tuple,\n buffered=buffered,\n follow_redirects=follow_redirects,\n )\n\n def __enter__(self) -> \"FlaskClient\":\n if self.preserve_context:\n raise RuntimeError(\"Cannot nest client invocations\")\n self.preserve_context = True\n return self\n\n def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n self.preserve_context = False\n\n # Normally the request context is preserved until the next\n # request in the same thread comes. When the client exits we\n # want to clean up earlier. Pop request contexts until the stack\n # is empty or a non-preserved one is found.\n while True:\n top = _request_ctx_stack.top\n\n if top is not None and top.preserved:\n top.pop()\n else:\n break"},{"col":4,"comment":"When used in combination with a ``with`` statement this opens a\n session transaction. This can be used to modify the session that\n the test client uses. Once the ``with`` block is left the session is\n stored back.\n\n ::\n\n with client.session_transaction() as session:\n session['value'] = 42\n\n Internally this is implemented by going through a temporary test\n request context and since session handling could depend on\n request variables this function accepts the same arguments as\n :meth:`~flask.Flask.test_request_context` which are directly\n passed through.\n ","endLoc":172,"header":"@contextmanager\n def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Generator[SessionMixin, None, None]","id":881,"name":"session_transaction","nodeType":"Function","startLoc":119,"text":"@contextmanager\n def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Generator[SessionMixin, None, None]:\n \"\"\"When used in combination with a ``with`` statement this opens a\n session transaction. This can be used to modify the session that\n the test client uses. Once the ``with`` block is left the session is\n stored back.\n\n ::\n\n with client.session_transaction() as session:\n session['value'] = 42\n\n Internally this is implemented by going through a temporary test\n request context and since session handling could depend on\n request variables this function accepts the same arguments as\n :meth:`~flask.Flask.test_request_context` which are directly\n passed through.\n \"\"\"\n if self.cookie_jar is None:\n raise RuntimeError(\n \"Session transactions only make sense with cookies enabled.\"\n )\n app = self.application\n environ_overrides = kwargs.setdefault(\"environ_overrides\", {})\n self.cookie_jar.inject_wsgi(environ_overrides)\n outer_reqctx = _request_ctx_stack.top\n with app.test_request_context(*args, **kwargs) as c:\n session_interface = app.session_interface\n sess = session_interface.open_session(app, c.request)\n if sess is None:\n raise RuntimeError(\n \"Session backend did not open a session. Check the configuration\"\n )\n\n # Since we have to open a new request context for the session\n # handling we want to make sure that we hide out own context\n # from the caller. By pushing the original request context\n # (or None) on top of this and popping it we get exactly that\n # behavior. It's important to not use the push and pop\n # methods of the actual request context object since that would\n # mean that cleanup handlers are called\n _request_ctx_stack.push(outer_reqctx)\n try:\n yield sess\n finally:\n _request_ctx_stack.pop()\n\n resp = app.response_class()\n if not session_interface.is_null_session(sess):\n session_interface.save_session(app, sess, resp)\n headers = resp.get_wsgi_headers(c.request.environ)\n self.cookie_jar.extract_wsgi(c.request.environ, headers)"},{"col":0,"comment":"Create a fake site-packages.","endLoc":153,"header":"@pytest.fixture\ndef site_packages(modules_tmpdir, monkeypatch)","id":882,"name":"site_packages","nodeType":"Function","startLoc":144,"text":"@pytest.fixture\ndef site_packages(modules_tmpdir, monkeypatch):\n \"\"\"Create a fake site-packages.\"\"\"\n rv = (\n modules_tmpdir.mkdir(\"lib\")\n .mkdir(f\"python{sys.version_info.major}.{sys.version_info.minor}\")\n .mkdir(\"site-packages\")\n )\n monkeypatch.syspath_prepend(str(rv))\n return rv"},{"col":0,"comment":"null","endLoc":34,"header":"def _lookup_req_object(name)","id":883,"name":"_lookup_req_object","nodeType":"Function","startLoc":30,"text":"def _lookup_req_object(name):\n top = _request_ctx_stack.top\n if top is None:\n raise RuntimeError(_request_ctx_err_msg)\n return getattr(top, name)"},{"col":0,"comment":"null","endLoc":41,"header":"def _lookup_app_object(name)","id":884,"name":"_lookup_app_object","nodeType":"Function","startLoc":37,"text":"def _lookup_app_object(name):\n top = _app_ctx_stack.top\n if top is None:\n raise RuntimeError(_app_ctx_err_msg)\n return getattr(top, name)"},{"col":0,"comment":"null","endLoc":48,"header":"def _find_app()","id":885,"name":"_find_app","nodeType":"Function","startLoc":44,"text":"def _find_app():\n top = _app_ctx_stack.top\n if top is None:\n raise RuntimeError(_app_ctx_err_msg)\n return top.app"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":886,"name":"_request_ctx_err_msg","nodeType":"Attribute","startLoc":13,"text":"_request_ctx_err_msg"},{"col":0,"comment":"Generate egg from package name inside base and put the egg into\n sys.path.","endLoc":189,"header":"@pytest.fixture\ndef install_egg(modules_tmpdir, monkeypatch)","id":887,"name":"install_egg","nodeType":"Function","startLoc":156,"text":"@pytest.fixture\ndef install_egg(modules_tmpdir, monkeypatch):\n \"\"\"Generate egg from package name inside base and put the egg into\n sys.path.\"\"\"\n\n def inner(name, base=modules_tmpdir):\n base.join(name).ensure_dir()\n base.join(name).join(\"__init__.py\").ensure()\n\n egg_setup = base.join(\"setup.py\")\n egg_setup.write(\n textwrap.dedent(\n f\"\"\"\n from setuptools import setup\n setup(\n name=\"{name}\",\n version=\"1.0\",\n packages=[\"site_egg\"],\n zip_safe=True,\n )\n \"\"\"\n )\n )\n\n import subprocess\n\n subprocess.check_call(\n [sys.executable, \"setup.py\", \"bdist_egg\"], cwd=str(modules_tmpdir)\n )\n (egg_path,) = modules_tmpdir.join(\"dist/\").listdir()\n monkeypatch.syspath_prepend(str(egg_path))\n return egg_path\n\n return inner"},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":888,"name":"_app_ctx_err_msg","nodeType":"Attribute","startLoc":20,"text":"_app_ctx_err_msg"},{"col":0,"comment":"","endLoc":1,"header":"globals.py#","id":889,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n from .ctx import _AppCtxGlobals\n from .sessions import SessionMixin\n from .wrappers import Request\n\n_request_ctx_err_msg = \"\"\"\\\nWorking outside of request context.\n\nThis typically means that you attempted to use functionality that needed\nan active HTTP request. Consult the documentation on testing for\ninformation about how to avoid this problem.\\\n\"\"\"\n\n_app_ctx_err_msg = \"\"\"\\\nWorking outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in some way. To solve\nthis, set up an application context with app.app_context(). See the\ndocumentation for more information.\\\n\"\"\"\n\n_request_ctx_stack = LocalStack()\n\n_app_ctx_stack = LocalStack()\n\ncurrent_app: \"Flask\" = LocalProxy(_find_app) # type: ignore\n\nrequest: \"Request\" = LocalProxy(partial(_lookup_req_object, \"request\")) # type: ignore\n\nsession: \"SessionMixin\" = LocalProxy( # type: ignore\n partial(_lookup_req_object, \"session\")\n)\n\ng: \"_AppCtxGlobals\" = LocalProxy(partial(_lookup_app_object, \"g\")) # type: ignore"},{"col":4,"comment":"null","endLoc":462,"header":"def __enter__(self) -> \"RequestContext\"","id":890,"name":"__enter__","nodeType":"Function","startLoc":460,"text":"def __enter__(self) -> \"RequestContext\":\n self.push()\n return self"},{"fileName":"wsgi.py","filePath":"tests/test_apps/helloworld","id":891,"nodeType":"File","text":"from hello import app # noqa: F401\n"},{"col":4,"comment":"null","endLoc":472,"header":"def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None","id":892,"name":"__exit__","nodeType":"Function","startLoc":464,"text":"def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n # do not pop the request stack if we are in debug mode and an\n # exception happened. This will allow the debugger to still\n # access the request object in the interactive shell. Furthermore\n # the context can be force kept alive for the test client.\n # See flask.testing for how this works.\n self.auto_pop(exc_value)"},{"id":893,"name":"examples/javascript/js_example","nodeType":"Package"},{"fileName":"__init__.py","filePath":"examples/javascript/js_example","id":894,"nodeType":"File","text":"from flask import Flask\n\napp = Flask(__name__)\n\nfrom js_example import views # noqa: F401\n"},{"col":0,"comment":"null","endLoc":197,"header":"@pytest.fixture\ndef purge_module(request)","id":895,"name":"purge_module","nodeType":"Function","startLoc":192,"text":"@pytest.fixture\ndef purge_module(request):\n def inner(name):\n request.addfinalizer(lambda: sys.modules.pop(name, None))\n\n return inner"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":896,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"col":29,"endLoc":195,"id":897,"nodeType":"Lambda","startLoc":195,"text":"lambda: sys.modules.pop(name, None)"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":898,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)"},{"attributeType":"null","col":27,"comment":"null","endLoc":10,"id":899,"name":"_Flask","nodeType":"Attribute","startLoc":10,"text":"_Flask"},{"col":4,"comment":"null","endLoc":478,"header":"def __repr__(self) -> str","id":900,"name":"__repr__","nodeType":"Function","startLoc":474,"text":"def __repr__(self) -> str:\n return (\n f\"<{type(self).__name__} {self.request.url!r}\"\n f\" [{self.request.method}] of {self.app.name}>\"\n )"},{"id":901,"name":"lazyloading.rst","nodeType":"TextFile","path":"docs/patterns","text":"Lazily Loading Views\n====================\n\nFlask is usually used with the decorators. Decorators are simple and you\nhave the URL right next to the function that is called for that specific\nURL. However there is a downside to this approach: it means all your code\nthat uses decorators has to be imported upfront or Flask will never\nactually find your function.\n\nThis can be a problem if your application has to import quick. It might\nhave to do that on systems like Google's App Engine or other systems. So\nif you suddenly notice that your application outgrows this approach you\ncan fall back to a centralized URL mapping.\n\nThe system that enables having a central URL map is the\n:meth:`~flask.Flask.add_url_rule` function. Instead of using decorators,\nyou have a file that sets up the application with all URLs.\n\nConverting to Centralized URL Map\n---------------------------------\n\nImagine the current application looks somewhat like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n @app.route('/')\n def index():\n pass\n\n @app.route('/user/')\n def user(username):\n pass\n\nThen, with the centralized approach you would have one file with the views\n(:file:`views.py`) but without any decorator::\n\n def index():\n pass\n\n def user(username):\n pass\n\nAnd then a file that sets up an application which maps the functions to\nURLs::\n\n from flask import Flask\n from yourapplication import views\n app = Flask(__name__)\n app.add_url_rule('/', view_func=views.index)\n app.add_url_rule('/user/', view_func=views.user)\n\nLoading Late\n------------\n\nSo far we only split up the views and the routing, but the module is still\nloaded upfront. The trick is to actually load the view function as needed.\nThis can be accomplished with a helper class that behaves just like a\nfunction but internally imports the real function on first use::\n\n from werkzeug.utils import import_string, cached_property\n\n class LazyView(object):\n\n def __init__(self, import_name):\n self.__module__, self.__name__ = import_name.rsplit('.', 1)\n self.import_name = import_name\n\n @cached_property\n def view(self):\n return import_string(self.import_name)\n\n def __call__(self, *args, **kwargs):\n return self.view(*args, **kwargs)\n\nWhat's important here is is that `__module__` and `__name__` are properly\nset. This is used by Flask internally to figure out how to name the\nURL rules in case you don't provide a name for the rule yourself.\n\nThen you can define your central place to combine the views like this::\n\n from flask import Flask\n from yourapplication.helpers import LazyView\n app = Flask(__name__)\n app.add_url_rule('/',\n view_func=LazyView('yourapplication.views.index'))\n app.add_url_rule('/user/',\n view_func=LazyView('yourapplication.views.user'))\n\nYou can further optimize this in terms of amount of keystrokes needed to\nwrite this by having a function that calls into\n:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project\nname and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::\n\n def url(import_name, url_rules=[], **options):\n view = LazyView(f\"yourapplication.{import_name}\")\n for url_rule in url_rules:\n app.add_url_rule(url_rule, view_func=view, **options)\n\n # add a single route to the index view\n url('views.index', ['/'])\n\n # add two routes to a single function endpoint\n url_rules = ['/user/','/user/']\n url('views.user', url_rules)\n\nOne thing to keep in mind is that before and after request handlers have\nto be in a file that is imported upfront to work properly on the first\nrequest. The same goes for any kind of remaining decorator.\n"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":303,"id":902,"name":"app","nodeType":"Attribute","startLoc":303,"text":"self.app"},{"attributeType":"None","col":8,"comment":"null","endLoc":306,"id":903,"name":"request","nodeType":"Attribute","startLoc":306,"text":"self.request"},{"attributeType":"null","col":8,"comment":"null","endLoc":332,"id":904,"name":"_after_request_functions","nodeType":"Attribute","startLoc":332,"text":"self._after_request_functions"},{"id":905,"name":"base.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"\nJavaScript Example\n\n\n\n\n
\n

{% block intro %}{% endblock %}

\n
\n
\n \n +\n \n \n
\n= \n{% block script %}{% endblock %}\n"},{"fileName":"__init__.py","filePath":"tests/test_apps/cliapp/inner1/inner2","id":906,"nodeType":"File","text":""},{"id":907,"name":"jquery.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"{% extends 'base.html' %}\n\n{% block intro %}\n jQuery is a popular library that\n adds cross browser APIs for common tasks. However, it requires loading\n an extra library.\n{% endblock %}\n\n{% block script %}\n \n \n{% endblock %}\n"},{"id":908,"name":"quickstart.rst","nodeType":"TextFile","path":"docs","text":"Quickstart\n==========\n\nEager to get started? This page gives a good introduction to Flask.\nFollow :doc:`installation` to set up a project and install Flask first.\n\n\nA Minimal Application\n---------------------\n\nA minimal Flask application looks something like this:\n\n.. code-block:: python\n\n from flask import Flask\n\n app = Flask(__name__)\n\n @app.route(\"/\")\n def hello_world():\n return \"

Hello, World!

\"\n\nSo what did that code do?\n\n1. First we imported the :class:`~flask.Flask` class. An instance of\n this class will be our WSGI application.\n2. Next we create an instance of this class. The first argument is the\n name of the application's module or package. ``__name__`` is a\n convenient shortcut for this that is appropriate for most cases.\n This is needed so that Flask knows where to look for resources such\n as templates and static files.\n3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask\n what URL should trigger our function.\n4. The function returns the message we want to display in the user's\n browser. The default content type is HTML, so HTML in the string\n will be rendered by the browser.\n\nSave it as :file:`hello.py` or something similar. Make sure to not call\nyour application :file:`flask.py` because this would conflict with Flask\nitself.\n\nTo run the application, use the :command:`flask` command or\n:command:`python -m flask`. Before you can do that you need\nto tell your terminal the application to work with by exporting the\n``FLASK_APP`` environment variable:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=hello\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=hello\n > flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"hello\"\n > flask run\n * Running on http://127.0.0.1:5000/\n\n.. admonition:: Application Discovery Behavior\n\n As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you\n don't have to set the ``FLASK_APP`` environment variable. See\n :doc:`/cli` for more details.\n\nThis launches a very simple builtin server, which is good enough for\ntesting but probably not what you want to use in production. For\ndeployment options see :doc:`deploying/index`.\n\nNow head over to http://127.0.0.1:5000/, and you should see your hello\nworld greeting.\n\n.. _public-server:\n\n.. admonition:: Externally Visible Server\n\n If you run the server you will notice that the server is only accessible\n from your own computer, not from any other in the network. This is the\n default because in debugging mode a user of the application can execute\n arbitrary Python code on your computer.\n\n If you have the debugger disabled or trust the users on your network,\n you can make the server publicly available simply by adding\n ``--host=0.0.0.0`` to the command line::\n\n $ flask run --host=0.0.0.0\n\n This tells your operating system to listen on all public IPs.\n\n\nWhat to do if the Server does not Start\n---------------------------------------\n\nIn case the :command:`python -m flask` fails or :command:`flask`\ndoes not exist, there are multiple reasons this might be the case.\nFirst of all you need to look at the error message.\n\nOld Version of Flask\n````````````````````\n\nVersions of Flask older than 0.11 used to have different ways to start the\napplication. In short, the :command:`flask` command did not exist, and\nneither did :command:`python -m flask`. In that case you have two options:\neither upgrade to newer Flask versions or have a look at :doc:`/server`\nto see the alternative method for running a server.\n\nInvalid Import Name\n```````````````````\n\nThe ``FLASK_APP`` environment variable is the name of the module to import at\n:command:`flask run`. In case that module is incorrectly named you will get an\nimport error upon start (or if debug is enabled when you navigate to the\napplication). It will tell you what it tried to import and why it failed.\n\nThe most common reason is a typo or because you did not actually create an\n``app`` object.\n\n\nDebug Mode\n----------\n\nThe ``flask run`` command can do more than just start the development\nserver. By enabling debug mode, the server will automatically reload if\ncode changes, and will show an interactive debugger in the browser if an\nerror occurs during a request.\n\n.. image:: _static/debugger.png\n :align: center\n :class: screenshot\n :alt: The interactive debugger in action.\n\n.. warning::\n\n The debugger allows executing arbitrary Python code from the\n browser. It is protected by a pin, but still represents a major\n security risk. Do not run the development server or debugger in a\n production environment.\n\nTo enable all development features, set the ``FLASK_ENV`` environment\nvariable to ``development`` before calling ``flask run``.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_ENV=development\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_ENV=development\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_ENV = \"development\"\n > flask run\n\nSee also:\n\n- :doc:`/server` and :doc:`/cli` for information about running in\n development mode.\n- :doc:`/debugging` for information about using the built-in debugger\n and other debuggers.\n- :doc:`/logging` and :doc:`/errorhandling` to log errors and display\n nice error pages.\n\n\nHTML Escaping\n-------------\n\nWhen returning HTML (the default response type in Flask), any\nuser-provided values rendered in the output must be escaped to protect\nfrom injection attacks. HTML templates rendered with Jinja, introduced\nlater, will do this automatically.\n\n:func:`~markupsafe.escape`, shown here, can be used manually. It is\nomitted in most examples for brevity, but you should always be aware of\nhow you're using untrusted data.\n\n.. code-block:: python\n\n from markupsafe import escape\n\n @app.route(\"/\")\n def hello(name):\n return f\"Hello, {escape(name)}!\"\n\nIf a user managed to submit the name ````,\nescaping causes it to be rendered as text, rather than running the\nscript in the user's browser.\n\n```` in the route captures a value from the URL and passes it to\nthe view function. These variable rules are explained below.\n\n\nRouting\n-------\n\nModern web applications use meaningful URLs to help users. Users are more\nlikely to like a page and come back if the page uses a meaningful URL they can\nremember and use to directly visit a page.\n\nUse the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::\n\n @app.route('/')\n def index():\n return 'Index Page'\n\n @app.route('/hello')\n def hello():\n return 'Hello, World'\n\nYou can do more! You can make parts of the URL dynamic and attach multiple\nrules to a function.\n\nVariable Rules\n``````````````\n\nYou can add variable sections to a URL by marking sections with\n````. Your function then receives the ````\nas a keyword argument. Optionally, you can use a converter to specify the type\nof the argument like ````. ::\n\n from markupsafe import escape\n\n @app.route('/user/')\n def show_user_profile(username):\n # show the user profile for that user\n return f'User {username}'\n\n @app.route('/post/')\n def show_post(post_id):\n # show the post with the given id, the id is an integer\n return f'Post {post_id}'\n\n @app.route('/path/')\n def show_subpath(subpath):\n # show the subpath after /path/\n return f'Subpath {subpath}'\n\nConverter types:\n\n========== ==========================================\n``string`` (default) accepts any text without a slash\n``int`` accepts positive integers\n``float`` accepts positive floating point values\n``path`` like ``string`` but also accepts slashes\n``uuid`` accepts UUID strings\n========== ==========================================\n\n\nUnique URLs / Redirection Behavior\n``````````````````````````````````\n\nThe following two rules differ in their use of a trailing slash. ::\n\n @app.route('/projects/')\n def projects():\n return 'The project page'\n\n @app.route('/about')\n def about():\n return 'The about page'\n\nThe canonical URL for the ``projects`` endpoint has a trailing slash.\nIt's similar to a folder in a file system. If you access the URL without\na trailing slash (``/projects``), Flask redirects you to the canonical URL\nwith the trailing slash (``/projects/``).\n\nThe canonical URL for the ``about`` endpoint does not have a trailing\nslash. It's similar to the pathname of a file. Accessing the URL with a\ntrailing slash (``/about/``) produces a 404 \"Not Found\" error. This helps\nkeep URLs unique for these resources, which helps search engines avoid\nindexing the same page twice.\n\n\n.. _url-building:\n\nURL Building\n````````````\n\nTo build a URL to a specific function, use the :func:`~flask.url_for` function.\nIt accepts the name of the function as its first argument and any number of\nkeyword arguments, each corresponding to a variable part of the URL rule.\nUnknown variable parts are appended to the URL as query parameters.\n\nWhy would you want to build URLs using the URL reversing function\n:func:`~flask.url_for` instead of hard-coding them into your templates?\n\n1. Reversing is often more descriptive than hard-coding the URLs.\n2. You can change your URLs in one go instead of needing to remember to\n manually change hard-coded URLs.\n3. URL building handles escaping of special characters transparently.\n4. The generated paths are always absolute, avoiding unexpected behavior\n of relative paths in browsers.\n5. If your application is placed outside the URL root, for example, in\n ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly\n handles that for you.\n\nFor example, here we use the :meth:`~flask.Flask.test_request_context` method\nto try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`\ntells Flask to behave as though it's handling a request even while we use a\nPython shell. See :ref:`context-locals`.\n\n.. code-block:: python\n\n from flask import url_for\n\n @app.route('/')\n def index():\n return 'index'\n\n @app.route('/login')\n def login():\n return 'login'\n\n @app.route('/user/')\n def profile(username):\n return f'{username}\\'s profile'\n\n with app.test_request_context():\n print(url_for('index'))\n print(url_for('login'))\n print(url_for('login', next='/'))\n print(url_for('profile', username='John Doe'))\n\n.. code-block:: text\n\n /\n /login\n /login?next=/\n /user/John%20Doe\n\n\nHTTP Methods\n````````````\n\nWeb applications use different HTTP methods when accessing URLs. You should\nfamiliarize yourself with the HTTP methods as you work with Flask. By default,\na route only answers to ``GET`` requests. You can use the ``methods`` argument\nof the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.\n::\n\n from flask import request\n\n @app.route('/login', methods=['GET', 'POST'])\n def login():\n if request.method == 'POST':\n return do_the_login()\n else:\n return show_the_login_form()\n\nIf ``GET`` is present, Flask automatically adds support for the ``HEAD`` method\nand handles ``HEAD`` requests according to the `HTTP RFC`_. Likewise,\n``OPTIONS`` is automatically implemented for you.\n\n.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt\n\nStatic Files\n------------\n\nDynamic web applications also need static files. That's usually where\nthe CSS and JavaScript files are coming from. Ideally your web server is\nconfigured to serve them for you, but during development Flask can do that\nas well. Just create a folder called :file:`static` in your package or next to\nyour module and it will be available at ``/static`` on the application.\n\nTo generate URLs for static files, use the special ``'static'`` endpoint name::\n\n url_for('static', filename='style.css')\n\nThe file has to be stored on the filesystem as :file:`static/style.css`.\n\nRendering Templates\n-------------------\n\nGenerating HTML from within Python is not fun, and actually pretty\ncumbersome because you have to do the HTML escaping on your own to keep\nthe application secure. Because of that Flask configures the `Jinja2\n`_ template engine for you automatically.\n\nTo render a template you can use the :func:`~flask.render_template`\nmethod. All you have to do is provide the name of the template and the\nvariables you want to pass to the template engine as keyword arguments.\nHere's a simple example of how to render a template::\n\n from flask import render_template\n\n @app.route('/hello/')\n @app.route('/hello/')\n def hello(name=None):\n return render_template('hello.html', name=name)\n\nFlask will look for templates in the :file:`templates` folder. So if your\napplication is a module, this folder is next to that module, if it's a\npackage it's actually inside your package:\n\n**Case 1**: a module::\n\n /application.py\n /templates\n /hello.html\n\n**Case 2**: a package::\n\n /application\n /__init__.py\n /templates\n /hello.html\n\nFor templates you can use the full power of Jinja2 templates. Head over\nto the official `Jinja2 Template Documentation\n`_ for more information.\n\nHere is an example template:\n\n.. sourcecode:: html+jinja\n\n \n Hello from Flask\n {% if name %}\n

Hello {{ name }}!

\n {% else %}\n

Hello, World!

\n {% endif %}\n\nInside templates you also have access to the :class:`~flask.request`,\n:class:`~flask.session` and :class:`~flask.g` [#]_ objects\nas well as the :func:`~flask.get_flashed_messages` function.\n\nTemplates are especially useful if inheritance is used. If you want to\nknow how that works, see :doc:`patterns/templateinheritance`. Basically\ntemplate inheritance makes it possible to keep certain elements on each\npage (like header, navigation and footer).\n\nAutomatic escaping is enabled, so if ``name`` contains HTML it will be escaped\nautomatically. If you can trust a variable and you know that it will be\nsafe HTML (for example because it came from a module that converts wiki\nmarkup to HTML) you can mark it as safe by using the\n:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the\ntemplate. Head over to the Jinja 2 documentation for more examples.\n\nHere is a basic introduction to how the :class:`~markupsafe.Markup` class works::\n\n >>> from markupsafe import Markup\n >>> Markup('Hello %s!') % 'hacker'\n Markup('Hello <blink>hacker</blink>!')\n >>> Markup.escape('hacker')\n Markup('<blink>hacker</blink>')\n >>> Markup('Marked up » HTML').striptags()\n 'Marked up \\xbb HTML'\n\n.. versionchanged:: 0.5\n\n Autoescaping is no longer enabled for all templates. The following\n extensions for templates trigger autoescaping: ``.html``, ``.htm``,\n ``.xml``, ``.xhtml``. Templates loaded from a string will have\n autoescaping disabled.\n\n.. [#] Unsure what that :class:`~flask.g` object is? It's something in which\n you can store information for your own needs. See the documentation\n for :class:`flask.g` and :doc:`patterns/sqlite3`.\n\n\nAccessing Request Data\n----------------------\n\nFor web applications it's crucial to react to the data a client sends to\nthe server. In Flask this information is provided by the global\n:class:`~flask.request` object. If you have some experience with Python\nyou might be wondering how that object can be global and how Flask\nmanages to still be threadsafe. The answer is context locals:\n\n\n.. _context-locals:\n\nContext Locals\n``````````````\n\n.. admonition:: Insider Information\n\n If you want to understand how that works and how you can implement\n tests with context locals, read this section, otherwise just skip it.\n\nCertain objects in Flask are global objects, but not of the usual kind.\nThese objects are actually proxies to objects that are local to a specific\ncontext. What a mouthful. But that is actually quite easy to understand.\n\nImagine the context being the handling thread. A request comes in and the\nweb server decides to spawn a new thread (or something else, the\nunderlying object is capable of dealing with concurrency systems other\nthan threads). When Flask starts its internal request handling it\nfigures out that the current thread is the active context and binds the\ncurrent application and the WSGI environments to that context (thread).\nIt does that in an intelligent way so that one application can invoke another\napplication without breaking.\n\nSo what does this mean to you? Basically you can completely ignore that\nthis is the case unless you are doing something like unit testing. You\nwill notice that code which depends on a request object will suddenly break\nbecause there is no request object. The solution is creating a request\nobject yourself and binding it to the context. The easiest solution for\nunit testing is to use the :meth:`~flask.Flask.test_request_context`\ncontext manager. In combination with the ``with`` statement it will bind a\ntest request so that you can interact with it. Here is an example::\n\n from flask import request\n\n with app.test_request_context('/hello', method='POST'):\n # now you can do something with the request until the\n # end of the with block, such as basic assertions:\n assert request.path == '/hello'\n assert request.method == 'POST'\n\nThe other possibility is passing a whole WSGI environment to the\n:meth:`~flask.Flask.request_context` method::\n\n with app.request_context(environ):\n assert request.method == 'POST'\n\nThe Request Object\n``````````````````\n\nThe request object is documented in the API section and we will not cover\nit here in detail (see :class:`~flask.Request`). Here is a broad overview of\nsome of the most common operations. First of all you have to import it from\nthe ``flask`` module::\n\n from flask import request\n\nThe current request method is available by using the\n:attr:`~flask.Request.method` attribute. To access form data (data\ntransmitted in a ``POST`` or ``PUT`` request) you can use the\n:attr:`~flask.Request.form` attribute. Here is a full example of the two\nattributes mentioned above::\n\n @app.route('/login', methods=['POST', 'GET'])\n def login():\n error = None\n if request.method == 'POST':\n if valid_login(request.form['username'],\n request.form['password']):\n return log_the_user_in(request.form['username'])\n else:\n error = 'Invalid username/password'\n # the code below is executed if the request method\n # was GET or the credentials were invalid\n return render_template('login.html', error=error)\n\nWhat happens if the key does not exist in the ``form`` attribute? In that\ncase a special :exc:`KeyError` is raised. You can catch it like a\nstandard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request\nerror page is shown instead. So for many situations you don't have to\ndeal with that problem.\n\nTo access parameters submitted in the URL (``?key=value``) you can use the\n:attr:`~flask.Request.args` attribute::\n\n searchword = request.args.get('key', '')\n\nWe recommend accessing URL parameters with `get` or by catching the\n:exc:`KeyError` because users might change the URL and presenting them a 400\nbad request page in that case is not user friendly.\n\nFor a full list of methods and attributes of the request object, head over\nto the :class:`~flask.Request` documentation.\n\n\nFile Uploads\n````````````\n\nYou can handle uploaded files with Flask easily. Just make sure not to\nforget to set the ``enctype=\"multipart/form-data\"`` attribute on your HTML\nform, otherwise the browser will not transmit your files at all.\n\nUploaded files are stored in memory or at a temporary location on the\nfilesystem. You can access those files by looking at the\n:attr:`~flask.request.files` attribute on the request object. Each\nuploaded file is stored in that dictionary. It behaves just like a\nstandard Python :class:`file` object, but it also has a\n:meth:`~werkzeug.datastructures.FileStorage.save` method that\nallows you to store that file on the filesystem of the server.\nHere is a simple example showing how that works::\n\n from flask import request\n\n @app.route('/upload', methods=['GET', 'POST'])\n def upload_file():\n if request.method == 'POST':\n f = request.files['the_file']\n f.save('/var/www/uploads/uploaded_file.txt')\n ...\n\nIf you want to know how the file was named on the client before it was\nuploaded to your application, you can access the\n:attr:`~werkzeug.datastructures.FileStorage.filename` attribute.\nHowever please keep in mind that this value can be forged\nso never ever trust that value. If you want to use the filename\nof the client to store the file on the server, pass it through the\n:func:`~werkzeug.utils.secure_filename` function that\nWerkzeug provides for you::\n\n from werkzeug.utils import secure_filename\n\n @app.route('/upload', methods=['GET', 'POST'])\n def upload_file():\n if request.method == 'POST':\n file = request.files['the_file']\n file.save(f\"/var/www/uploads/{secure_filename(f.filename)}\")\n ...\n\nFor some better examples, see :doc:`patterns/fileuploads`.\n\nCookies\n```````\n\nTo access cookies you can use the :attr:`~flask.Request.cookies`\nattribute. To set cookies you can use the\n:attr:`~flask.Response.set_cookie` method of response objects. The\n:attr:`~flask.Request.cookies` attribute of request objects is a\ndictionary with all the cookies the client transmits. If you want to use\nsessions, do not use the cookies directly but instead use the\n:ref:`sessions` in Flask that add some security on top of cookies for you.\n\nReading cookies::\n\n from flask import request\n\n @app.route('/')\n def index():\n username = request.cookies.get('username')\n # use cookies.get(key) instead of cookies[key] to not get a\n # KeyError if the cookie is missing.\n\nStoring cookies::\n\n from flask import make_response\n\n @app.route('/')\n def index():\n resp = make_response(render_template(...))\n resp.set_cookie('username', 'the username')\n return resp\n\nNote that cookies are set on response objects. Since you normally\njust return strings from the view functions Flask will convert them into\nresponse objects for you. If you explicitly want to do that you can use\nthe :meth:`~flask.make_response` function and then modify it.\n\nSometimes you might want to set a cookie at a point where the response\nobject does not exist yet. This is possible by utilizing the\n:doc:`patterns/deferredcallbacks` pattern.\n\nFor this also see :ref:`about-responses`.\n\nRedirects and Errors\n--------------------\n\nTo redirect a user to another endpoint, use the :func:`~flask.redirect`\nfunction; to abort a request early with an error code, use the\n:func:`~flask.abort` function::\n\n from flask import abort, redirect, url_for\n\n @app.route('/')\n def index():\n return redirect(url_for('login'))\n\n @app.route('/login')\n def login():\n abort(401)\n this_is_never_executed()\n\nThis is a rather pointless example because a user will be redirected from\nthe index to a page they cannot access (401 means access denied) but it\nshows how that works.\n\nBy default a black and white error page is shown for each error code. If\nyou want to customize the error page, you can use the\n:meth:`~flask.Flask.errorhandler` decorator::\n\n from flask import render_template\n\n @app.errorhandler(404)\n def page_not_found(error):\n return render_template('page_not_found.html'), 404\n\nNote the ``404`` after the :func:`~flask.render_template` call. This\ntells Flask that the status code of that page should be 404 which means\nnot found. By default 200 is assumed which translates to: all went well.\n\nSee :doc:`errorhandling` for more details.\n\n.. _about-responses:\n\nAbout Responses\n---------------\n\nThe return value from a view function is automatically converted into\na response object for you. If the return value is a string it's\nconverted into a response object with the string as response body, a\n``200 OK`` status code and a :mimetype:`text/html` mimetype. If the\nreturn value is a dict, :func:`jsonify` is called to produce a response.\nThe logic that Flask applies to converting return values into response\nobjects is as follows:\n\n1. If a response object of the correct type is returned it's directly\n returned from the view.\n2. If it's a string, a response object is created with that data and\n the default parameters.\n3. If it's a dict, a response object is created using ``jsonify``.\n4. If a tuple is returned the items in the tuple can provide extra\n information. Such tuples have to be in the form\n ``(response, status)``, ``(response, headers)``, or\n ``(response, status, headers)``. The ``status`` value will override\n the status code and ``headers`` can be a list or dictionary of\n additional header values.\n5. If none of that works, Flask will assume the return value is a\n valid WSGI application and convert that into a response object.\n\nIf you want to get hold of the resulting response object inside the view\nyou can use the :func:`~flask.make_response` function.\n\nImagine you have a view like this::\n\n from flask import render_template\n\n @app.errorhandler(404)\n def not_found(error):\n return render_template('error.html'), 404\n\nYou just need to wrap the return expression with\n:func:`~flask.make_response` and get the response object to modify it, then\nreturn it::\n\n from flask import make_response\n\n @app.errorhandler(404)\n def not_found(error):\n resp = make_response(render_template('error.html'), 404)\n resp.headers['X-Something'] = 'A value'\n return resp\n\n\nAPIs with JSON\n``````````````\n\nA common response format when writing an API is JSON. It's easy to get\nstarted writing such an API with Flask. If you return a ``dict`` from a\nview, it will be converted to a JSON response.\n\n.. code-block:: python\n\n @app.route(\"/me\")\n def me_api():\n user = get_current_user()\n return {\n \"username\": user.username,\n \"theme\": user.theme,\n \"image\": url_for(\"user_image\", filename=user.image),\n }\n\nDepending on your API design, you may want to create JSON responses for\ntypes other than ``dict``. In that case, use the\n:func:`~flask.json.jsonify` function, which will serialize any supported\nJSON data type. Or look into Flask community extensions that support\nmore complex applications.\n\n.. code-block:: python\n\n from flask import jsonify\n\n @app.route(\"/users\")\n def users_api():\n users = get_all_users()\n return jsonify([user.to_json() for user in users])\n\n\n.. _sessions:\n\nSessions\n--------\n\nIn addition to the request object there is also a second object called\n:class:`~flask.session` which allows you to store information specific to a\nuser from one request to the next. This is implemented on top of cookies\nfor you and signs the cookies cryptographically. What this means is that\nthe user could look at the contents of your cookie but not modify it,\nunless they know the secret key used for signing.\n\nIn order to use sessions you have to set a secret key. Here is how\nsessions work::\n\n from flask import session\n\n # Set the secret key to some random bytes. Keep this really secret!\n app.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\n @app.route('/')\n def index():\n if 'username' in session:\n return f'Logged in as {session[\"username\"]}'\n return 'You are not logged in'\n\n @app.route('/login', methods=['GET', 'POST'])\n def login():\n if request.method == 'POST':\n session['username'] = request.form['username']\n return redirect(url_for('index'))\n return '''\n
\n

\n

\n

\n '''\n\n @app.route('/logout')\n def logout():\n # remove the username from the session if it's there\n session.pop('username', None)\n return redirect(url_for('index'))\n\n.. admonition:: How to generate good secret keys\n\n A secret key should be as random as possible. Your operating system has\n ways to generate pretty random data based on a cryptographic random\n generator. Use the following command to quickly generate a value for\n :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::\n\n $ python -c 'import os; print(os.urandom(16))'\n b'_5#y2L\"F4Q8z\\n\\xec]/'\n\nA note on cookie-based sessions: Flask will take the values you put into the\nsession object and serialize them into a cookie. If you are finding some\nvalues do not persist across requests, cookies are indeed enabled, and you are\nnot getting a clear error message, check the size of the cookie in your page\nresponses compared to the size supported by web browsers.\n\nBesides the default client-side based sessions, if you want to handle\nsessions on the server-side instead, there are several\nFlask extensions that support this.\n\nMessage Flashing\n----------------\n\nGood applications and user interfaces are all about feedback. If the user\ndoes not get enough feedback they will probably end up hating the\napplication. Flask provides a really simple way to give feedback to a\nuser with the flashing system. The flashing system basically makes it\npossible to record a message at the end of a request and access it on the next\n(and only the next) request. This is usually combined with a layout\ntemplate to expose the message.\n\nTo flash a message use the :func:`~flask.flash` method, to get hold of the\nmessages you can use :func:`~flask.get_flashed_messages` which is also\navailable in the templates. See :doc:`patterns/flashing` for a full\nexample.\n\nLogging\n-------\n\n.. versionadded:: 0.3\n\nSometimes you might be in a situation where you deal with data that\nshould be correct, but actually is not. For example you may have\nsome client-side code that sends an HTTP request to the server\nbut it's obviously malformed. This might be caused by a user tampering\nwith the data, or the client code failing. Most of the time it's okay\nto reply with ``400 Bad Request`` in that situation, but sometimes\nthat won't do and the code has to continue working.\n\nYou may still want to log that something fishy happened. This is where\nloggers come in handy. As of Flask 0.3 a logger is preconfigured for you\nto use.\n\nHere are some example log calls::\n\n app.logger.debug('A value for debugging')\n app.logger.warning('A warning occurred (%d apples)', 42)\n app.logger.error('An error occurred')\n\nThe attached :attr:`~flask.Flask.logger` is a standard logging\n:class:`~logging.Logger`, so head over to the official :mod:`logging`\ndocs for more information.\n\nSee :doc:`errorhandling`.\n\n\nHooking in WSGI Middleware\n--------------------------\n\nTo add WSGI middleware to your Flask application, wrap the application's\n``wsgi_app`` attribute. For example, to apply Werkzeug's\n:class:`~werkzeug.middleware.proxy_fix.ProxyFix` middleware for running\nbehind Nginx:\n\n.. code-block:: python\n\n from werkzeug.middleware.proxy_fix import ProxyFix\n app.wsgi_app = ProxyFix(app.wsgi_app)\n\nWrapping ``app.wsgi_app`` instead of ``app`` means that ``app`` still\npoints at your Flask application, not at the middleware, so you can\ncontinue to use and configure ``app`` directly.\n\nUsing Flask Extensions\n----------------------\n\nExtensions are packages that help you accomplish common tasks. For\nexample, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple\nand easy to use with Flask.\n\nFor more on Flask extensions, see :doc:`extensions`.\n\nDeploying to a Web Server\n-------------------------\n\nReady to deploy your new Flask app? See :doc:`deploying/index`.\n"},{"fileName":"views.py","filePath":"examples/javascript/js_example","id":909,"nodeType":"File","text":"from flask import jsonify\nfrom flask import render_template\nfrom flask import request\n\nfrom js_example import app\n\n\n@app.route(\"/\", defaults={\"js\": \"plain\"})\n@app.route(\"/\")\ndef index(js):\n return render_template(f\"{js}.html\", js=js)\n\n\n@app.route(\"/add\", methods=[\"POST\"])\ndef add():\n a = request.form.get(\"a\", 0, type=float)\n b = request.form.get(\"b\", 0, type=float)\n return jsonify(result=a + b)\n"},{"id":910,"name":"changes.rst","nodeType":"TextFile","path":"docs","text":"Changes\n=======\n\n.. include:: ../CHANGES.rst\n"},{"col":0,"comment":"null","endLoc":11,"header":"@app.route(\"/\", defaults={\"js\": \"plain\"})\n@app.route(\"/\")\ndef index(js):\n return render_template(f\"{js}.html\", js=js)"},{"attributeType":"null","col":8,"comment":"null","endLoc":319,"id":912,"name":"_implicit_app_ctx_stack","nodeType":"Attribute","startLoc":319,"text":"self._implicit_app_ctx_stack"},{"attributeType":"None","col":8,"comment":"null","endLoc":313,"id":913,"name":"session","nodeType":"Attribute","startLoc":313,"text":"self.session"},{"col":0,"comment":"null","endLoc":18,"header":"@app.route(\"/add\", methods=[\"POST\"])\ndef add()","id":914,"name":"add","nodeType":"Function","startLoc":14,"text":"@app.route(\"/add\", methods=[\"POST\"])\ndef add():\n a = request.form.get(\"a\", 0, type=float)\n b = request.form.get(\"b\", 0, type=float)\n return jsonify(result=a + b)"},{"attributeType":"null","col":8,"comment":"null","endLoc":323,"id":915,"name":"preserved","nodeType":"Attribute","startLoc":323,"text":"self.preserved"},{"id":916,"name":"docs.txt","nodeType":"TextFile","path":"requirements","text":"#\n# This file is autogenerated by pip-compile\n# To update, run:\n#\n# pip-compile requirements/docs.in\n#\nalabaster==0.7.12\n # via sphinx\nbabel==2.9.1\n # via sphinx\ncertifi==2020.12.5\n # via requests\nchardet==4.0.0\n # via requests\ndocutils==0.16\n # via\n # sphinx\n # sphinx-tabs\nidna==2.10\n # via requests\nimagesize==1.2.0\n # via sphinx\njinja2==3.0.0\n # via sphinx\nmarkupsafe==2.0.0\n # via jinja2\npackaging==20.9\n # via\n # pallets-sphinx-themes\n # sphinx\npallets-sphinx-themes==2.0.0\n # via -r requirements/docs.in\npygments==2.9.0\n # via\n # sphinx\n # sphinx-tabs\npyparsing==2.4.7\n # via packaging\npytz==2021.1\n # via babel\nrequests==2.25.1\n # via sphinx\nsnowballstemmer==2.1.0\n # via sphinx\nsphinx-issues==1.2.0\n # via -r requirements/docs.in\nsphinx-tabs==3.0.0\n # via -r requirements/docs.in\ngit+https://github.com/sphinx-doc/sphinx.git@96dbe5e3\n # via\n # -r requirements/docs.in\n # pallets-sphinx-themes\n # sphinx-issues\n # sphinx-tabs\n # sphinxcontrib-log-cabinet\nsphinxcontrib-applehelp==1.0.2\n # via sphinx\nsphinxcontrib-devhelp==1.0.2\n # via sphinx\nsphinxcontrib-htmlhelp==1.0.3\n # via sphinx\nsphinxcontrib-jsmath==1.0.1\n # via sphinx\nsphinxcontrib-log-cabinet==1.0.1\n # via -r requirements/docs.in\nsphinxcontrib-qthelp==1.0.3\n # via sphinx\nsphinxcontrib-serializinghtml==1.1.4\n # via sphinx\nurllib3==1.26.4\n # via requests\n\n# The following packages are considered to be unsafe in a requirements file:\n# setuptools\n"},{"attributeType":"null","col":12,"comment":"null","endLoc":309,"id":917,"name":"url_adapter","nodeType":"Attribute","startLoc":309,"text":"self.url_adapter"},{"attributeType":"None","col":8,"comment":"null","endLoc":327,"id":918,"name":"_preserved_exc","nodeType":"Attribute","startLoc":327,"text":"self._preserved_exc"},{"id":919,"name":"appfactories.rst","nodeType":"TextFile","path":"docs/patterns","text":"Application Factories\n=====================\n\nIf you are already using packages and blueprints for your application\n(:doc:`/blueprints`) there are a couple of really nice ways to further improve\nthe experience. A common pattern is creating the application object when\nthe blueprint is imported. But if you move the creation of this object\ninto a function, you can then create multiple instances of this app later.\n\nSo why would you want to do this?\n\n1. Testing. You can have instances of the application with different\n settings to test every case.\n2. Multiple instances. Imagine you want to run different versions of the\n same application. Of course you could have multiple instances with\n different configs set up in your webserver, but if you use factories,\n you can have multiple instances of the same application running in the\n same application process which can be handy.\n\nSo how would you then actually implement that?\n\nBasic Factories\n---------------\n\nThe idea is to set up the application in a function. Like this::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n from yourapplication.model import db\n db.init_app(app)\n\n from yourapplication.views.admin import admin\n from yourapplication.views.frontend import frontend\n app.register_blueprint(admin)\n app.register_blueprint(frontend)\n\n return app\n\nThe downside is that you cannot use the application object in the blueprints\nat import time. You can however use it from within a request. How do you\nget access to the application with the config? Use\n:data:`~flask.current_app`::\n\n from flask import current_app, Blueprint, render_template\n admin = Blueprint('admin', __name__, url_prefix='/admin')\n\n @admin.route('/')\n def index():\n return render_template(current_app.config['INDEX_TEMPLATE'])\n\nHere we look up the name of a template in the config.\n\nFactories & Extensions\n----------------------\n\nIt's preferable to create your extensions and app factories so that the\nextension object does not initially get bound to the application.\n\nUsing `Flask-SQLAlchemy `_,\nas an example, you should not do something along those lines::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n db = SQLAlchemy(app)\n\nBut, rather, in model.py (or equivalent)::\n\n db = SQLAlchemy()\n\nand in your application.py (or equivalent)::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n from yourapplication.model import db\n db.init_app(app)\n\nUsing this design pattern, no application-specific state is stored on the\nextension object, so one extension object can be used for multiple apps.\nFor more information about the design of extensions refer to :doc:`/extensiondev`.\n\nUsing Applications\n------------------\n\nTo run such an application, you can use the :command:`flask` command:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=myapp\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=myapp\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"myapp\"\n > flask run\n\nFlask will automatically detect the factory (``create_app`` or ``make_app``)\nin ``myapp``. You can also pass arguments to the factory like this:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_APP=\"myapp:create_app('dev')\"\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_APP=\"myapp:create_app('dev')\"\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_APP = \"myapp:create_app('dev')\"\n > flask run\n\nThen the ``create_app`` factory in ``myapp`` is called with the string\n``'dev'`` as the argument. See :doc:`/cli` for more detail.\n\nFactory Improvements\n--------------------\n\nThe factory function above is not very clever, but you can improve it.\nThe following changes are straightforward to implement:\n\n1. Make it possible to pass in configuration values for unit tests so that\n you don't have to create config files on the filesystem.\n2. Call a function from a blueprint when the application is setting up so\n that you have a place to modify attributes of the application (like\n hooking in before/after request handlers etc.)\n3. Add in WSGI middlewares when the application is being created if necessary.\n"},{"id":920,"name":"MANIFEST.in","nodeType":"TextFile","path":"","text":"include CHANGES.rst\ninclude CONTRIBUTING.rst\ninclude tox.ini\ninclude requirements/*.txt\ngraft artwork\ngraft docs\nprune docs/_build\ngraft examples\ngraft tests\ninclude src/flask/py.typed\nglobal-exclude *.pyc\n"},{"attributeType":"None","col":8,"comment":"null","endLoc":312,"id":921,"name":"flashes","nodeType":"Attribute","startLoc":312,"text":"self.flashes"},{"id":922,"name":"foreword.rst","nodeType":"TextFile","path":"docs","text":"Foreword\n========\n\nRead this before you get started with Flask. This hopefully answers some\nquestions about the purpose and goals of the project, and when you\nshould or should not be using it.\n\nWhat does \"micro\" mean?\n-----------------------\n\n“Micro” does not mean that your whole web application has to fit into a single\nPython file (although it certainly can), nor does it mean that Flask is lacking\nin functionality. The \"micro\" in microframework means Flask aims to keep the\ncore simple but extensible. Flask won't make many decisions for you, such as\nwhat database to use. Those decisions that it does make, such as what\ntemplating engine to use, are easy to change. Everything else is up to you, so\nthat Flask can be everything you need and nothing you don't.\n\nBy default, Flask does not include a database abstraction layer, form\nvalidation or anything else where different libraries already exist that can\nhandle that. Instead, Flask supports extensions to add such functionality to\nyour application as if it was implemented in Flask itself. Numerous extensions\nprovide database integration, form validation, upload handling, various open\nauthentication technologies, and more. Flask may be \"micro\", but it's ready for\nproduction use on a variety of needs.\n\nConfiguration and Conventions\n-----------------------------\n\nFlask has many configuration values, with sensible defaults, and a few\nconventions when getting started. By convention, templates and static\nfiles are stored in subdirectories within the application's Python\nsource tree, with the names :file:`templates` and :file:`static`\nrespectively. While this can be changed, you usually don't have to,\nespecially when getting started.\n\nGrowing with Flask\n------------------\n\nOnce you have Flask up and running, you'll find a variety of extensions\navailable in the community to integrate your project for production.\n\nAs your codebase grows, you are free to make the design decisions appropriate\nfor your project. Flask will continue to provide a very simple glue layer to\nthe best that Python has to offer. You can implement advanced patterns in\nSQLAlchemy or another database tool, introduce non-relational data persistence\nas appropriate, and take advantage of framework-agnostic tools built for WSGI,\nthe Python web interface.\n\nFlask includes many hooks to customize its behavior. Should you need more\ncustomization, the Flask class is built for subclassing. If you are interested\nin that, check out the :doc:`becomingbig` chapter. If you are curious about\nthe Flask design principles, head over to the section about :doc:`design`.\n"},{"attributeType":"null","col":17,"comment":"null","endLoc":2,"id":923,"name":"t","nodeType":"Attribute","startLoc":2,"text":"t"},{"attributeType":"null","col":0,"comment":"null","endLoc":21,"id":924,"name":"_sentinel","nodeType":"Attribute","startLoc":21,"text":"_sentinel"},{"id":925,"name":"becomingbig.rst","nodeType":"TextFile","path":"docs","text":"Becoming Big\n============\n\nHere are your options when growing your codebase or scaling your application.\n\nRead the Source.\n----------------\n\nFlask started in part to demonstrate how to build your own framework on top of\nexisting well-used tools Werkzeug (WSGI) and Jinja (templating), and as it\ndeveloped, it became useful to a wide audience. As you grow your codebase,\ndon't just use Flask -- understand it. Read the source. Flask's code is\nwritten to be read; its documentation is published so you can use its internal\nAPIs. Flask sticks to documented APIs in upstream libraries, and documents its\ninternal utilities so that you can find the hook points needed for your\nproject.\n\nHook. Extend.\n-------------\n\nThe :doc:`/api` docs are full of available overrides, hook points, and\n:doc:`/signals`. You can provide custom classes for things like the\nrequest and response objects. Dig deeper on the APIs you use, and look\nfor the customizations which are available out of the box in a Flask\nrelease. Look for ways in which your project can be refactored into a\ncollection of utilities and Flask extensions. Explore the many\n:doc:`/extensions` in the community, and look for patterns to build your\nown extensions if you do not find the tools you need.\n\nSubclass.\n---------\n\nThe :class:`~flask.Flask` class has many methods designed for subclassing. You\ncan quickly add or customize behavior by subclassing :class:`~flask.Flask` (see\nthe linked method docs) and using that subclass wherever you instantiate an\napplication class. This works well with :doc:`/patterns/appfactories`.\nSee :doc:`/patterns/subclassing` for an example.\n\nWrap with middleware.\n---------------------\n\nThe :doc:`/patterns/appdispatch` pattern shows in detail how to apply middleware. You\ncan introduce WSGI middleware to wrap your Flask instances and introduce fixes\nand changes at the layer between your Flask application and your HTTP\nserver. Werkzeug includes several `middlewares\n`_.\n\nFork.\n-----\n\nIf none of the above options work, fork Flask. The majority of code of Flask\nis within Werkzeug and Jinja2. These libraries do the majority of the work.\nFlask is just the paste that glues those together. For every project there is\nthe point where the underlying framework gets in the way (due to assumptions\nthe original developers had). This is natural because if this would not be the\ncase, the framework would be a very complex system to begin with which causes a\nsteep learning curve and a lot of user frustration.\n\nThis is not unique to Flask. Many people use patched and modified\nversions of their framework to counter shortcomings. This idea is also\nreflected in the license of Flask. You don't have to contribute any\nchanges back if you decide to modify the framework.\n\nThe downside of forking is of course that Flask extensions will most\nlikely break because the new framework has a different import name.\nFurthermore integrating upstream changes can be a complex process,\ndepending on the number of changes. Because of that, forking should be\nthe very last resort.\n\nScale like a pro.\n-----------------\n\nFor many web applications the complexity of the code is less an issue than\nthe scaling for the number of users or data entries expected. Flask by\nitself is only limited in terms of scaling by your application code, the\ndata store you want to use and the Python implementation and webserver you\nare running on.\n\nScaling well means for example that if you double the amount of servers\nyou get about twice the performance. Scaling bad means that if you add a\nnew server the application won't perform any better or would not even\nsupport a second server.\n\nThere is only one limiting factor regarding scaling in Flask which are\nthe context local proxies. They depend on context which in Flask is\ndefined as being either a thread, process or greenlet. If your server\nuses some kind of concurrency that is not based on threads or greenlets,\nFlask will no longer be able to support these global proxies. However the\nmajority of servers are using either threads, greenlets or separate\nprocesses to achieve concurrency which are all methods well supported by\nthe underlying Werkzeug library.\n\nDiscuss with the community.\n---------------------------\n\nThe Flask developers keep the framework accessible to users with codebases big\nand small. If you find an obstacle in your way, caused by Flask, don't hesitate\nto contact the developers on the mailing list or Discord server. The best way for\nthe Flask and Flask extension developers to improve the tools for larger\napplications is getting feedback from users.\n"},{"id":926,"name":"setup.cfg","nodeType":"TextFile","path":"examples/javascript","text":"[metadata]\nname = js_example\nversion = 1.0.0\nurl = https://flask.palletsprojects.com/patterns/jquery/\nlicense = BSD-3-Clause\nmaintainer = Pallets\nmaintainer_email = contact@palletsprojects.com\ndescription = Demonstrates making AJAX requests to Flask.\nlong_description = file: README.rst\nlong_description_content_type = text/x-rst\n\n[options]\npackages = find:\ninclude_package_data = true\ninstall_requires =\n Flask\n\n[options.extras_require]\ntest =\n pytest\n blinker\n\n[tool:pytest]\ntestpaths = tests\n\n[coverage:run]\nbranch = True\nsource =\n js_example\n"},{"col":0,"comment":"","endLoc":1,"header":"ctx.py#","id":927,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n from .sessions import SessionMixin\n from .wrappers import Request\n\n_sentinel = object()"},{"fileName":"blog.py","filePath":"examples/tutorial/flaskr","id":928,"nodeType":"File","text":"from flask import Blueprint\nfrom flask import flash\nfrom flask import g\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\nfrom werkzeug.exceptions import abort\n\nfrom flaskr.auth import login_required\nfrom flaskr.db import get_db\n\nbp = Blueprint(\"blog\", __name__)\n\n\n@bp.route(\"/\")\ndef index():\n \"\"\"Show all the posts, most recent first.\"\"\"\n db = get_db()\n posts = db.execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY created DESC\"\n ).fetchall()\n return render_template(\"blog/index.html\", posts=posts)\n\n\ndef get_post(id, check_author=True):\n \"\"\"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n \"\"\"\n post = (\n get_db()\n .execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" WHERE p.id = ?\",\n (id,),\n )\n .fetchone()\n )\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post[\"author_id\"] != g.user[\"id\"]:\n abort(403)\n\n return post\n\n\n@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create():\n \"\"\"Create a new post for the current user.\"\"\"\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)\",\n (title, body, g.user[\"id\"]),\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/create.html\")\n\n\n@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id):\n \"\"\"Update a post if the current user is the author.\"\"\"\n post = get_post(id)\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"UPDATE post SET title = ?, body = ? WHERE id = ?\", (title, body, id)\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/update.html\", post=post)\n\n\n@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id):\n \"\"\"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n \"\"\"\n get_post(id)\n db = get_db()\n db.execute(\"DELETE FROM post WHERE id = ?\", (id,))\n db.commit()\n return redirect(url_for(\"blog.index\"))\n"},{"id":929,"name":"views.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nBlueprints and Views\n====================\n\nA view function is the code you write to respond to requests to your\napplication. Flask uses patterns to match the incoming request URL to\nthe view that should handle it. The view returns data that Flask turns\ninto an outgoing response. Flask can also go the other direction and\ngenerate a URL to a view based on its name and arguments.\n\n\nCreate a Blueprint\n------------------\n\nA :class:`Blueprint` is a way to organize a group of related views and\nother code. Rather than registering views and other code directly with\nan application, they are registered with a blueprint. Then the blueprint\nis registered with the application when it is available in the factory\nfunction.\n\nFlaskr will have two blueprints, one for authentication functions and\none for the blog posts functions. The code for each blueprint will go\nin a separate module. Since the blog needs to know about authentication,\nyou'll write the authentication one first.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n import functools\n\n from flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n )\n from werkzeug.security import check_password_hash, generate_password_hash\n\n from flaskr.db import get_db\n\n bp = Blueprint('auth', __name__, url_prefix='/auth')\n\nThis creates a :class:`Blueprint` named ``'auth'``. Like the application\nobject, the blueprint needs to know where it's defined, so ``__name__``\nis passed as the second argument. The ``url_prefix`` will be prepended\nto all the URLs associated with the blueprint.\n\nImport and register the blueprint from the factory using\n:meth:`app.register_blueprint() `. Place the\nnew code at the end of the factory function before returning the app.\n\n.. code-block:: python\n :caption: ``flaskr/__init__.py``\n\n def create_app():\n app = ...\n # existing code omitted\n\n from . import auth\n app.register_blueprint(auth.bp)\n\n return app\n\nThe authentication blueprint will have views to register new users and\nto log in and log out.\n\n\nThe First View: Register\n------------------------\n\nWhen the user visits the ``/auth/register`` URL, the ``register`` view\nwill return `HTML`_ with a form for them to fill out. When they submit\nthe form, it will validate their input and either show the form again\nwith an error message or create the new user and go to the login page.\n\n.. _HTML: https://developer.mozilla.org/docs/Web/HTML\n\nFor now you will just write the view code. On the next page, you'll\nwrite templates to generate the HTML form.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/register', methods=('GET', 'POST'))\n def register():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n db = get_db()\n error = None\n\n if not username:\n error = 'Username is required.'\n elif not password:\n error = 'Password is required.'\n elif db.execute(\n 'SELECT id FROM user WHERE username = ?', (username,)\n ).fetchone() is not None:\n error = f\"User {username} is already registered.\"\n\n if error is None:\n db.execute(\n 'INSERT INTO user (username, password) VALUES (?, ?)',\n (username, generate_password_hash(password))\n )\n db.commit()\n return redirect(url_for('auth.login'))\n\n flash(error)\n\n return render_template('auth/register.html')\n\nHere's what the ``register`` view function is doing:\n\n#. :meth:`@bp.route ` associates the URL ``/register``\n with the ``register`` view function. When Flask receives a request\n to ``/auth/register``, it will call the ``register`` view and use\n the return value as the response.\n\n#. If the user submitted the form,\n :attr:`request.method ` will be ``'POST'``. In this\n case, start validating the input.\n\n#. :attr:`request.form ` is a special type of\n :class:`dict` mapping submitted form keys and values. The user will\n input their ``username`` and ``password``.\n\n#. Validate that ``username`` and ``password`` are not empty.\n\n#. Validate that ``username`` is not already registered by querying the\n database and checking if a result is returned.\n :meth:`db.execute ` takes a SQL query\n with ``?`` placeholders for any user input, and a tuple of values\n to replace the placeholders with. The database library will take\n care of escaping the values so you are not vulnerable to a\n *SQL injection attack*.\n\n :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.\n If the query returned no results, it returns ``None``. Later,\n :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of\n all results.\n\n#. If validation succeeds, insert the new user data into the database.\n For security, passwords should never be stored in the database\n directly. Instead,\n :func:`~werkzeug.security.generate_password_hash` is used to\n securely hash the password, and that hash is stored. Since this\n query modifies data, :meth:`db.commit() `\n needs to be called afterwards to save the changes.\n\n#. After storing the user, they are redirected to the login page.\n :func:`url_for` generates the URL for the login view based on its\n name. This is preferable to writing the URL directly as it allows\n you to change the URL later without changing all code that links to\n it. :func:`redirect` generates a redirect response to the generated\n URL.\n\n#. If validation fails, the error is shown to the user. :func:`flash`\n stores messages that can be retrieved when rendering the template.\n\n#. When the user initially navigates to ``auth/register``, or\n there was a validation error, an HTML page with the registration\n form should be shown. :func:`render_template` will render a template\n containing the HTML, which you'll write in the next step of the\n tutorial.\n\n\nLogin\n-----\n\nThis view follows the same pattern as the ``register`` view above.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/login', methods=('GET', 'POST'))\n def login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n db = get_db()\n error = None\n user = db.execute(\n 'SELECT * FROM user WHERE username = ?', (username,)\n ).fetchone()\n\n if user is None:\n error = 'Incorrect username.'\n elif not check_password_hash(user['password'], password):\n error = 'Incorrect password.'\n\n if error is None:\n session.clear()\n session['user_id'] = user['id']\n return redirect(url_for('index'))\n\n flash(error)\n\n return render_template('auth/login.html')\n\nThere are a few differences from the ``register`` view:\n\n#. The user is queried first and stored in a variable for later use.\n\n#. :func:`~werkzeug.security.check_password_hash` hashes the submitted\n password in the same way as the stored hash and securely compares\n them. If they match, the password is valid.\n\n#. :data:`session` is a :class:`dict` that stores data across requests.\n When validation succeeds, the user's ``id`` is stored in a new\n session. The data is stored in a *cookie* that is sent to the\n browser, and the browser then sends it back with subsequent requests.\n Flask securely *signs* the data so that it can't be tampered with.\n\nNow that the user's ``id`` is stored in the :data:`session`, it will be\navailable on subsequent requests. At the beginning of each request, if\na user is logged in their information should be loaded and made\navailable to other views.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.before_app_request\n def load_logged_in_user():\n user_id = session.get('user_id')\n\n if user_id is None:\n g.user = None\n else:\n g.user = get_db().execute(\n 'SELECT * FROM user WHERE id = ?', (user_id,)\n ).fetchone()\n\n:meth:`bp.before_app_request() ` registers\na function that runs before the view function, no matter what URL is\nrequested. ``load_logged_in_user`` checks if a user id is stored in the\n:data:`session` and gets that user's data from the database, storing it\non :data:`g.user `, which lasts for the length of the request. If\nthere is no user id, or if the id doesn't exist, ``g.user`` will be\n``None``.\n\n\nLogout\n------\n\nTo log out, you need to remove the user id from the :data:`session`.\nThen ``load_logged_in_user`` won't load a user on subsequent requests.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/logout')\n def logout():\n session.clear()\n return redirect(url_for('index'))\n\n\nRequire Authentication in Other Views\n-------------------------------------\n\nCreating, editing, and deleting blog posts will require a user to be\nlogged in. A *decorator* can be used to check this for each view it's\napplied to.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n def login_required(view):\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for('auth.login'))\n\n return view(**kwargs)\n\n return wrapped_view\n\nThis decorator returns a new view function that wraps the original view\nit's applied to. The new function checks if a user is loaded and\nredirects to the login page otherwise. If a user is loaded the original\nview is called and continues normally. You'll use this decorator when\nwriting the blog views.\n\nEndpoints and URLs\n------------------\n\nThe :func:`url_for` function generates the URL to a view based on a name\nand arguments. The name associated with a view is also called the\n*endpoint*, and by default it's the same as the name of the view\nfunction.\n\nFor example, the ``hello()`` view that was added to the app\nfactory earlier in the tutorial has the name ``'hello'`` and can be\nlinked to with ``url_for('hello')``. If it took an argument, which\nyou'll see later, it would be linked to using\n``url_for('hello', who='World')``.\n\nWhen using a blueprint, the name of the blueprint is prepended to the\nname of the function, so the endpoint for the ``login`` function you\nwrote above is ``'auth.login'`` because you added it to the ``'auth'``\nblueprint.\n\nContinue to :doc:`templates`.\n"},{"id":930,"name":"pull_request_template.md","nodeType":"TextFile","path":".github","text":"\n\n\n\n- fixes #\n\n\n\nChecklist:\n\n- [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.\n- [ ] Add or update relevant docs, in the docs folder and in code.\n- [ ] Add an entry in `CHANGES.rst` summarizing the change and linking to the issue.\n- [ ] Add `.. versionchanged::` entries in any relevant code docs.\n- [ ] Run `pre-commit` hooks and fix any issues.\n- [ ] Run `pytest` and `tox`, no tests failed.\n"},{"id":931,"name":"register.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/auth","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Register{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n{% endblock %}\n"},{"fileName":"testing.py","filePath":"src/flask","id":932,"nodeType":"File","text":"import typing as t\nfrom contextlib import contextmanager\nfrom copy import copy\nfrom types import TracebackType\n\nimport werkzeug.test\nfrom click.testing import CliRunner\nfrom werkzeug.test import Client\nfrom werkzeug.urls import url_parse\nfrom werkzeug.wrappers import Request as BaseRequest\n\nfrom . import _request_ctx_stack\nfrom .cli import ScriptInfo\nfrom .json import dumps as json_dumps\nfrom .sessions import SessionMixin\n\nif t.TYPE_CHECKING:\n from .app import Flask\n from .wrappers import Response\n\n\nclass EnvironBuilder(werkzeug.test.EnvironBuilder):\n \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n application.\n\n :param app: The Flask application to configure the environment from.\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n\n def __init__(\n self,\n app: \"Flask\",\n path: str = \"/\",\n base_url: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_scheme: t.Optional[str] = None,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> None:\n assert not (base_url or subdomain or url_scheme) or (\n base_url is not None\n ) != bool(\n subdomain or url_scheme\n ), 'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n\n if base_url is None:\n http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n app_root = app.config[\"APPLICATION_ROOT\"]\n\n if subdomain:\n http_host = f\"{subdomain}.{http_host}\"\n\n if url_scheme is None:\n url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n url = url_parse(path)\n base_url = (\n f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n f\"/{app_root.lstrip('/')}\"\n )\n path = url.path\n\n if url.query:\n sep = b\"?\" if isinstance(url.query, bytes) else \"?\"\n path += sep + url.query\n\n self.app = app\n super().__init__(path, base_url, *args, **kwargs)\n\n def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore\n \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n The serialization will be configured according to the config associated\n with this EnvironBuilder's ``app``.\n \"\"\"\n kwargs.setdefault(\"app\", self.app)\n return json_dumps(obj, **kwargs)\n\n\nclass FlaskClient(Client):\n \"\"\"Works like a regular Werkzeug test client but has some knowledge about\n how Flask works to defer the cleanup of the request context stack to the\n end of a ``with`` body when used in a ``with`` statement. For general\n information about how to use this class refer to\n :class:`werkzeug.test.Client`.\n\n .. versionchanged:: 0.12\n `app.test_client()` includes preset default environment, which can be\n set after instantiation of the `app.test_client()` object in\n `client.environ_base`.\n\n Basic usage is outlined in the :doc:`/testing` chapter.\n \"\"\"\n\n application: \"Flask\"\n preserve_context = False\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.environ_base = {\n \"REMOTE_ADDR\": \"127.0.0.1\",\n \"HTTP_USER_AGENT\": f\"werkzeug/{werkzeug.__version__}\",\n }\n\n @contextmanager\n def session_transaction(\n self, *args: t.Any, **kwargs: t.Any\n ) -> t.Generator[SessionMixin, None, None]:\n \"\"\"When used in combination with a ``with`` statement this opens a\n session transaction. This can be used to modify the session that\n the test client uses. Once the ``with`` block is left the session is\n stored back.\n\n ::\n\n with client.session_transaction() as session:\n session['value'] = 42\n\n Internally this is implemented by going through a temporary test\n request context and since session handling could depend on\n request variables this function accepts the same arguments as\n :meth:`~flask.Flask.test_request_context` which are directly\n passed through.\n \"\"\"\n if self.cookie_jar is None:\n raise RuntimeError(\n \"Session transactions only make sense with cookies enabled.\"\n )\n app = self.application\n environ_overrides = kwargs.setdefault(\"environ_overrides\", {})\n self.cookie_jar.inject_wsgi(environ_overrides)\n outer_reqctx = _request_ctx_stack.top\n with app.test_request_context(*args, **kwargs) as c:\n session_interface = app.session_interface\n sess = session_interface.open_session(app, c.request)\n if sess is None:\n raise RuntimeError(\n \"Session backend did not open a session. Check the configuration\"\n )\n\n # Since we have to open a new request context for the session\n # handling we want to make sure that we hide out own context\n # from the caller. By pushing the original request context\n # (or None) on top of this and popping it we get exactly that\n # behavior. It's important to not use the push and pop\n # methods of the actual request context object since that would\n # mean that cleanup handlers are called\n _request_ctx_stack.push(outer_reqctx)\n try:\n yield sess\n finally:\n _request_ctx_stack.pop()\n\n resp = app.response_class()\n if not session_interface.is_null_session(sess):\n session_interface.save_session(app, sess, resp)\n headers = resp.get_wsgi_headers(c.request.environ)\n self.cookie_jar.extract_wsgi(c.request.environ, headers)\n\n def open( # type: ignore\n self,\n *args: t.Any,\n as_tuple: bool = False,\n buffered: bool = False,\n follow_redirects: bool = False,\n **kwargs: t.Any,\n ) -> \"Response\":\n # Same logic as super.open, but apply environ_base and preserve_context.\n request = None\n\n def copy_environ(other):\n return {\n **self.environ_base,\n **other,\n \"flask._preserve_context\": self.preserve_context,\n }\n\n if not kwargs and len(args) == 1:\n arg = args[0]\n\n if isinstance(arg, werkzeug.test.EnvironBuilder):\n builder = copy(arg)\n builder.environ_base = copy_environ(builder.environ_base or {})\n request = builder.get_request()\n elif isinstance(arg, dict):\n request = EnvironBuilder.from_environ(\n arg, app=self.application, environ_base=copy_environ({})\n ).get_request()\n elif isinstance(arg, BaseRequest):\n request = copy(arg)\n request.environ = copy_environ(request.environ)\n\n if request is None:\n kwargs[\"environ_base\"] = copy_environ(kwargs.get(\"environ_base\", {}))\n builder = EnvironBuilder(self.application, *args, **kwargs)\n\n try:\n request = builder.get_request()\n finally:\n builder.close()\n\n return super().open( # type: ignore\n request,\n as_tuple=as_tuple,\n buffered=buffered,\n follow_redirects=follow_redirects,\n )\n\n def __enter__(self) -> \"FlaskClient\":\n if self.preserve_context:\n raise RuntimeError(\"Cannot nest client invocations\")\n self.preserve_context = True\n return self\n\n def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n self.preserve_context = False\n\n # Normally the request context is preserved until the next\n # request in the same thread comes. When the client exits we\n # want to clean up earlier. Pop request contexts until the stack\n # is empty or a non-preserved one is found.\n while True:\n top = _request_ctx_stack.top\n\n if top is not None and top.preserved:\n top.pop()\n else:\n break\n\n\nclass FlaskCliRunner(CliRunner):\n \"\"\"A :class:`~click.testing.CliRunner` for testing a Flask app's\n CLI commands. Typically created using\n :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.\n \"\"\"\n\n def __init__(self, app: \"Flask\", **kwargs: t.Any) -> None:\n self.app = app\n super().__init__(**kwargs)\n\n def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n \"\"\"\n if cli is None:\n cli = self.app.cli\n\n if \"obj\" not in kwargs:\n kwargs[\"obj\"] = ScriptInfo(create_app=lambda: self.app)\n\n return super().invoke(cli, args, **kwargs)\n"},{"id":933,"name":"_macro.html","nodeType":"TextFile","path":"tests/templates","text":"{% macro hello(name) %}Hello {{ name }}!{% endmacro %}\n"},{"id":934,"name":"bug-report.md","nodeType":"TextFile","path":".github/ISSUE_TEMPLATE","text":"---\nname: Bug report\nabout: Report a bug in Flask (not other projects which depend on Flask)\n---\n\n\n\n\n\n\n\nEnvironment:\n\n- Python version:\n- Flask version:\n"},{"id":935,"name":"uwsgi.rst","nodeType":"TextFile","path":"docs/deploying","text":"uWSGI\n=====\n\nuWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and\n`cherokee`_; see :doc:`fastcgi` and :doc:`wsgi-standalone` for other options.\nTo use your WSGI application with uWSGI protocol you will need a uWSGI server\nfirst. uWSGI is both a protocol and an application server; the application\nserver can serve uWSGI, FastCGI, and HTTP protocols.\n\nThe most popular uWSGI server is `uwsgi`_, which we will use for this\nguide. Make sure to have it installed to follow along.\n\n.. admonition:: Watch Out\n\n Please make sure in advance that any ``app.run()`` calls you might\n have in your application file are inside an ``if __name__ ==\n '__main__':`` block or moved to a separate file. Just make sure it's\n not called because this will always start a local WSGI server which\n we do not want if we deploy that application to uWSGI.\n\nStarting your app with uwsgi\n----------------------------\n\n`uwsgi` is designed to operate on WSGI callables found in python modules.\n\nGiven a flask application in myapp.py, use the following command:\n\n.. sourcecode:: text\n\n $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app\n\nThe ``--manage-script-name`` will move the handling of ``SCRIPT_NAME``\nto uwsgi, since it is smarter about that.\nIt is used together with the ``--mount`` directive which will make\nrequests to ``/yourapplication`` be directed to ``myapp:app``.\nIf your application is accessible at root level, you can use a\nsingle ``/`` instead of ``/yourapplication``. ``myapp`` refers to the name of\nthe file of your flask application (without extension) or the module which\nprovides ``app``. ``app`` is the callable inside of your application (usually\nthe line reads ``app = Flask(__name__)``.\n\nIf you want to deploy your flask application inside of a virtual environment,\nyou need to also add ``--virtualenv /path/to/virtual/environment``. You might\nalso need to add ``--plugin python`` or ``--plugin python3`` depending on which\npython version you use for your project.\n\nConfiguring nginx\n-----------------\n\nA basic flask nginx configuration looks like this::\n\n location = /yourapplication { rewrite ^ /yourapplication/; }\n location /yourapplication { try_files $uri @yourapplication; }\n location @yourapplication {\n include uwsgi_params;\n uwsgi_pass unix:/tmp/yourapplication.sock;\n }\n\nThis configuration binds the application to ``/yourapplication``. If you want\nto have it in the URL root its a bit simpler::\n\n location / { try_files $uri @yourapplication; }\n location @yourapplication {\n include uwsgi_params;\n uwsgi_pass unix:/tmp/yourapplication.sock;\n }\n\n.. _nginx: https://nginx.org/\n.. _lighttpd: https://www.lighttpd.net/\n.. _cherokee: http://cherokee-project.com/\n.. _uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/\n"},{"id":936,"name":"README.rst","nodeType":"TextFile","path":"examples/tutorial","text":"Flaskr\n======\n\nThe basic blog app built in the Flask `tutorial`_.\n\n.. _tutorial: https://flask.palletsprojects.com/tutorial/\n\n\nInstall\n-------\n\n**Be sure to use the same version of the code as the version of the docs\nyou're reading.** You probably want the latest tagged version, but the\ndefault Git version is the main branch. ::\n\n # clone the repository\n $ git clone https://github.com/pallets/flask\n $ cd flask\n # checkout the correct version\n $ git tag # shows the tagged versions\n $ git checkout latest-tag-found-above\n $ cd examples/tutorial\n\nCreate a virtualenv and activate it::\n\n $ python3 -m venv venv\n $ . venv/bin/activate\n\nOr on Windows cmd::\n\n $ py -3 -m venv venv\n $ venv\\Scripts\\activate.bat\n\nInstall Flaskr::\n\n $ pip install -e .\n\nOr if you are using the main branch, install Flask from source before\ninstalling Flaskr::\n\n $ pip install -e ../..\n $ pip install -e .\n\n\nRun\n---\n\n::\n\n $ export FLASK_APP=flaskr\n $ export FLASK_ENV=development\n $ flask init-db\n $ flask run\n\nOr on Windows cmd::\n\n > set FLASK_APP=flaskr\n > set FLASK_ENV=development\n > flask init-db\n > flask run\n\nOpen http://127.0.0.1:5000 in a browser.\n\n\nTest\n----\n\n::\n\n $ pip install '.[test]'\n $ pytest\n\nRun with coverage report::\n\n $ coverage run -m pytest\n $ coverage report\n $ coverage html # open htmlcov/index.html in a browser\n"},{"className":"EnvironBuilder","col":0,"comment":"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n application.\n\n :param app: The Flask application to configure the environment from.\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n ","endLoc":91,"id":937,"nodeType":"Class","startLoc":22,"text":"class EnvironBuilder(werkzeug.test.EnvironBuilder):\n \"\"\"An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the\n application.\n\n :param app: The Flask application to configure the environment from.\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n\n def __init__(\n self,\n app: \"Flask\",\n path: str = \"/\",\n base_url: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_scheme: t.Optional[str] = None,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> None:\n assert not (base_url or subdomain or url_scheme) or (\n base_url is not None\n ) != bool(\n subdomain or url_scheme\n ), 'Cannot pass \"subdomain\" or \"url_scheme\" with \"base_url\".'\n\n if base_url is None:\n http_host = app.config.get(\"SERVER_NAME\") or \"localhost\"\n app_root = app.config[\"APPLICATION_ROOT\"]\n\n if subdomain:\n http_host = f\"{subdomain}.{http_host}\"\n\n if url_scheme is None:\n url_scheme = app.config[\"PREFERRED_URL_SCHEME\"]\n\n url = url_parse(path)\n base_url = (\n f\"{url.scheme or url_scheme}://{url.netloc or http_host}\"\n f\"/{app_root.lstrip('/')}\"\n )\n path = url.path\n\n if url.query:\n sep = b\"?\" if isinstance(url.query, bytes) else \"?\"\n path += sep + url.query\n\n self.app = app\n super().__init__(path, base_url, *args, **kwargs)\n\n def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore\n \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n The serialization will be configured according to the config associated\n with this EnvironBuilder's ``app``.\n \"\"\"\n kwargs.setdefault(\"app\", self.app)\n return json_dumps(obj, **kwargs)"},{"id":938,"name":"data.sql","nodeType":"TextFile","path":"examples/tutorial/tests","text":"INSERT INTO user (username, password)\nVALUES\n ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),\n ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');\n\nINSERT INTO post (title, body, author_id, created)\nVALUES\n ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');\n"},{"id":939,"name":"LICENSE.rst","nodeType":"TextFile","path":"artwork","text":"Copyright 2010 Pallets\n\nThis logo or a modified version may be used by anyone to refer to the\nFlask project, but does not indicate endorsement by the project.\n\nRedistribution and use in source (SVG) and binary (renders in PNG, etc.)\nforms, with or without modification, are permitted provided that the\nfollowing conditions are met:\n\n1. Redistributions of source code must retain the above copyright\n notice and this list of conditions.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nWe would appreciate that you make the image a link to\nhttps://palletsprojects.com/p/flask/ if you use it in a medium that\nsupports links.\n"},{"col":4,"comment":"Serialize ``obj`` to a JSON-formatted string.\n\n The serialization will be configured according to the config associated\n with this EnvironBuilder's ``app``.\n ","endLoc":91,"header":"def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str","id":940,"name":"json_dumps","nodeType":"Function","startLoc":84,"text":"def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore\n \"\"\"Serialize ``obj`` to a JSON-formatted string.\n\n The serialization will be configured according to the config associated\n with this EnvironBuilder's ``app``.\n \"\"\"\n kwargs.setdefault(\"app\", self.app)\n return json_dumps(obj, **kwargs)"},{"attributeType":"null","col":8,"comment":"null","endLoc":380,"id":941,"name":"data","nodeType":"Attribute","startLoc":380,"text":"self.data"},{"attributeType":"null","col":8,"comment":"null","endLoc":374,"id":942,"name":"app_import_path","nodeType":"Attribute","startLoc":374,"text":"self.app_import_path"},{"attributeType":"None","col":8,"comment":"null","endLoc":382,"id":943,"name":"_loaded_app","nodeType":"Attribute","startLoc":382,"text":"self._loaded_app"},{"attributeType":"null","col":8,"comment":"null","endLoc":377,"id":944,"name":"create_app","nodeType":"Attribute","startLoc":377,"text":"self.create_app"},{"col":0,"comment":"Show all the posts, most recent first.","endLoc":25,"header":"@bp.route(\"/\")\ndef index()","id":945,"name":"index","nodeType":"Function","startLoc":16,"text":"@bp.route(\"/\")\ndef index():\n \"\"\"Show all the posts, most recent first.\"\"\"\n db = get_db()\n posts = db.execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY created DESC\"\n ).fetchall()\n return render_template(\"blog/index.html\", posts=posts)"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":81,"id":946,"name":"app","nodeType":"Attribute","startLoc":81,"text":"self.app"},{"attributeType":"null","col":8,"comment":"null","endLoc":381,"id":947,"name":"set_debug_flag","nodeType":"Attribute","startLoc":381,"text":"self.set_debug_flag"},{"attributeType":"None","col":4,"comment":"null","endLoc":45,"id":948,"name":"methods","nodeType":"Attribute","startLoc":45,"text":"methods"},{"className":"FlaskGroup","col":0,"comment":"Special subclass of the :class:`AppGroup` group that supports\n loading more commands from the configured Flask app. Normally a\n developer does not have to interface with this class but there are\n some very advanced use cases for which it makes sense to create an\n instance of this. see :ref:`custom-scripts`.\n\n :param add_default_commands: if this is True then the default run and\n shell commands will be added.\n :param add_version_option: adds the ``--version`` option.\n :param create_app: an optional callback that is passed the script info and\n returns the loaded app.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param set_debug_flag: Set the app's debug flag based on the active\n environment\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment variables\n from :file:`.env` and :file:`.flaskenv` files.\n ","endLoc":596,"id":949,"nodeType":"Class","startLoc":476,"text":"class FlaskGroup(AppGroup):\n \"\"\"Special subclass of the :class:`AppGroup` group that supports\n loading more commands from the configured Flask app. Normally a\n developer does not have to interface with this class but there are\n some very advanced use cases for which it makes sense to create an\n instance of this. see :ref:`custom-scripts`.\n\n :param add_default_commands: if this is True then the default run and\n shell commands will be added.\n :param add_version_option: adds the ``--version`` option.\n :param create_app: an optional callback that is passed the script info and\n returns the loaded app.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param set_debug_flag: Set the app's debug flag based on the active\n environment\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment variables\n from :file:`.env` and :file:`.flaskenv` files.\n \"\"\"\n\n def __init__(\n self,\n add_default_commands=True,\n create_app=None,\n add_version_option=True,\n load_dotenv=True,\n set_debug_flag=True,\n **extra,\n ):\n params = list(extra.pop(\"params\", None) or ())\n\n if add_version_option:\n params.append(version_option)\n\n AppGroup.__init__(self, params=params, **extra)\n self.create_app = create_app\n self.load_dotenv = load_dotenv\n self.set_debug_flag = set_debug_flag\n\n if add_default_commands:\n self.add_command(run_command)\n self.add_command(shell_command)\n self.add_command(routes_command)\n\n self._loaded_plugin_commands = False\n\n def _load_plugin_commands(self):\n if self._loaded_plugin_commands:\n return\n try:\n import pkg_resources\n except ImportError:\n self._loaded_plugin_commands = True\n return\n\n for ep in pkg_resources.iter_entry_points(\"flask.commands\"):\n self.add_command(ep.load(), ep.name)\n self._loaded_plugin_commands = True\n\n def get_command(self, ctx, name):\n self._load_plugin_commands()\n # Look up built-in and plugin commands, which should be\n # available even if the app fails to load.\n rv = super().get_command(ctx, name)\n\n if rv is not None:\n return rv\n\n info = ctx.ensure_object(ScriptInfo)\n\n # Look up commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n return info.load_app().cli.get_command(ctx, name)\n except NoAppException as e:\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n\n def list_commands(self, ctx):\n self._load_plugin_commands()\n # Start with the built-in and plugin commands.\n rv = set(super().list_commands(ctx))\n info = ctx.ensure_object(ScriptInfo)\n\n # Add commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n rv.update(info.load_app().cli.list_commands(ctx))\n except NoAppException as e:\n # When an app couldn't be loaded, show the error message\n # without the traceback.\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n except Exception:\n # When any other errors occurred during loading, show the\n # full traceback.\n click.secho(f\"{traceback.format_exc()}\\n\", err=True, fg=\"red\")\n\n return sorted(rv)\n\n def main(self, *args, **kwargs):\n # Set a global flag that indicates that we were invoked from the\n # command line interface. This is detected by Flask.run to make the\n # call into a no-op. This is necessary to avoid ugly errors when the\n # script that is loaded here also attempts to start a server.\n os.environ[\"FLASK_RUN_FROM_CLI\"] = \"true\"\n\n if get_load_dotenv(self.load_dotenv):\n load_dotenv()\n\n obj = kwargs.get(\"obj\")\n\n if obj is None:\n obj = ScriptInfo(\n create_app=self.create_app, set_debug_flag=self.set_debug_flag\n )\n\n kwargs[\"obj\"] = obj\n kwargs.setdefault(\"auto_envvar_prefix\", \"FLASK\")\n return super().main(*args, **kwargs)"},{"col":4,"comment":"null","endLoc":523,"header":"def __init__(\n self,\n add_default_commands=True,\n create_app=None,\n add_version_option=True,\n load_dotenv=True,\n set_debug_flag=True,\n **extra,\n )","id":950,"name":"__init__","nodeType":"Function","startLoc":499,"text":"def __init__(\n self,\n add_default_commands=True,\n create_app=None,\n add_version_option=True,\n load_dotenv=True,\n set_debug_flag=True,\n **extra,\n ):\n params = list(extra.pop(\"params\", None) or ())\n\n if add_version_option:\n params.append(version_option)\n\n AppGroup.__init__(self, params=params, **extra)\n self.create_app = create_app\n self.load_dotenv = load_dotenv\n self.set_debug_flag = set_debug_flag\n\n if add_default_commands:\n self.add_command(run_command)\n self.add_command(shell_command)\n self.add_command(routes_command)\n\n self._loaded_plugin_commands = False"},{"attributeType":"None","col":4,"comment":"null","endLoc":48,"id":951,"name":"provide_automatic_options","nodeType":"Attribute","startLoc":48,"text":"provide_automatic_options"},{"col":0,"comment":"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n ","endLoc":57,"header":"def get_post(id, check_author=True)","id":952,"name":"get_post","nodeType":"Function","startLoc":28,"text":"def get_post(id, check_author=True):\n \"\"\"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n \"\"\"\n post = (\n get_db()\n .execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" WHERE p.id = ?\",\n (id,),\n )\n .fetchone()\n )\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post[\"author_id\"] != g.user[\"id\"]:\n abort(403)\n\n return post"},{"col":0,"comment":"Create a new post for the current user.","endLoc":83,"header":"@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create()","id":953,"name":"create","nodeType":"Function","startLoc":60,"text":"@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create():\n \"\"\"Create a new post for the current user.\"\"\"\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)\",\n (title, body, g.user[\"id\"]),\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/create.html\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":59,"id":954,"name":"decorators","nodeType":"Attribute","startLoc":59,"text":"decorators"},{"className":"MethodViewType","col":0,"comment":"Metaclass for :class:`MethodView` that determines what methods the view\n defines.\n ","endLoc":129,"id":955,"nodeType":"Class","startLoc":105,"text":"class MethodViewType(type):\n \"\"\"Metaclass for :class:`MethodView` that determines what methods the view\n defines.\n \"\"\"\n\n def __init__(cls, name, bases, d):\n super().__init__(name, bases, d)\n\n if \"methods\" not in d:\n methods = set()\n\n for base in bases:\n if getattr(base, \"methods\", None):\n methods.update(base.methods)\n\n for key in http_method_funcs:\n if hasattr(cls, key):\n methods.add(key.upper())\n\n # If we have no method at all in there we don't want to add a\n # method list. This is for instance the case for the base class\n # or another subclass of a base method view that does not introduce\n # new methods.\n if methods:\n cls.methods = methods"},{"col":4,"comment":"null","endLoc":129,"header":"def __init__(cls, name, bases, d)","id":956,"name":"__init__","nodeType":"Function","startLoc":110,"text":"def __init__(cls, name, bases, d):\n super().__init__(name, bases, d)\n\n if \"methods\" not in d:\n methods = set()\n\n for base in bases:\n if getattr(base, \"methods\", None):\n methods.update(base.methods)\n\n for key in http_method_funcs:\n if hasattr(cls, key):\n methods.add(key.upper())\n\n # If we have no method at all in there we don't want to add a\n # method list. This is for instance the case for the base class\n # or another subclass of a base method view that does not introduce\n # new methods.\n if methods:\n cls.methods = methods"},{"col":0,"comment":"Update a post if the current user is the author.","endLoc":110,"header":"@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id)","id":957,"name":"update","nodeType":"Function","startLoc":86,"text":"@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id):\n \"\"\"Update a post if the current user is the author.\"\"\"\n post = get_post(id)\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"UPDATE post SET title = ?, body = ? WHERE id = ?\", (title, body, id)\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/update.html\", post=post)"},{"className":"FlaskCliRunner","col":0,"comment":"A :class:`~click.testing.CliRunner` for testing a Flask app's\n CLI commands. Typically created using\n :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.\n ","endLoc":280,"id":958,"nodeType":"Class","startLoc":247,"text":"class FlaskCliRunner(CliRunner):\n \"\"\"A :class:`~click.testing.CliRunner` for testing a Flask app's\n CLI commands. Typically created using\n :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.\n \"\"\"\n\n def __init__(self, app: \"Flask\", **kwargs: t.Any) -> None:\n self.app = app\n super().__init__(**kwargs)\n\n def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n \"\"\"\n if cli is None:\n cli = self.app.cli\n\n if \"obj\" not in kwargs:\n kwargs[\"obj\"] = ScriptInfo(create_app=lambda: self.app)\n\n return super().invoke(cli, args, **kwargs)"},{"col":4,"comment":"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n ","endLoc":280,"header":"def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> t.Any","id":959,"name":"invoke","nodeType":"Function","startLoc":257,"text":"def invoke( # type: ignore\n self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"Invokes a CLI command in an isolated environment. See\n :meth:`CliRunner.invoke ` for\n full method documentation. See :ref:`testing-cli` for examples.\n\n If the ``obj`` argument is not given, passes an instance of\n :class:`~flask.cli.ScriptInfo` that knows how to load the Flask\n app being tested.\n\n :param cli: Command object to invoke. Default is the app's\n :attr:`~flask.app.Flask.cli` group.\n :param args: List of strings to invoke the command with.\n\n :return: a :class:`~click.testing.Result` object.\n \"\"\"\n if cli is None:\n cli = self.app.cli\n\n if \"obj\" not in kwargs:\n kwargs[\"obj\"] = ScriptInfo(create_app=lambda: self.app)\n\n return super().invoke(cli, args, **kwargs)"},{"col":50,"endLoc":278,"id":960,"nodeType":"Lambda","startLoc":278,"text":"lambda: self.app"},{"col":0,"comment":"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n ","endLoc":125,"header":"@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id)","id":961,"name":"delete","nodeType":"Function","startLoc":113,"text":"@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id):\n \"\"\"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n \"\"\"\n get_post(id)\n db = get_db()\n db.execute(\"DELETE FROM post WHERE id = ?\", (id,))\n db.commit()\n return redirect(url_for(\"blog.index\"))"},{"attributeType":"null","col":16,"comment":"null","endLoc":129,"id":962,"name":"methods","nodeType":"Attribute","startLoc":129,"text":"cls.methods"},{"className":"MethodView","col":0,"comment":"A class-based view that dispatches request methods to the corresponding\n class methods. For example, if you implement a ``get`` method, it will be\n used to handle ``GET`` requests. ::\n\n class CounterAPI(MethodView):\n def get(self):\n return session.get('counter', 0)\n\n def post(self):\n session['counter'] = session.get('counter', 0) + 1\n return 'OK'\n\n app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))\n ","endLoc":157,"id":963,"nodeType":"Class","startLoc":132,"text":"class MethodView(View, metaclass=MethodViewType):\n \"\"\"A class-based view that dispatches request methods to the corresponding\n class methods. For example, if you implement a ``get`` method, it will be\n used to handle ``GET`` requests. ::\n\n class CounterAPI(MethodView):\n def get(self):\n return session.get('counter', 0)\n\n def post(self):\n session['counter'] = session.get('counter', 0) + 1\n return 'OK'\n\n app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))\n \"\"\"\n\n def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n meth = getattr(self, request.method.lower(), None)\n\n # If the request method is HEAD and we don't have a handler for it\n # retry with GET.\n if meth is None and request.method == \"HEAD\":\n meth = getattr(self, \"get\", None)\n\n assert meth is not None, f\"Unimplemented method {request.method!r}\"\n return meth(*args, **kwargs)"},{"attributeType":"Flask","col":8,"comment":"null","endLoc":254,"id":964,"name":"app","nodeType":"Attribute","startLoc":254,"text":"self.app"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":965,"name":"bp","nodeType":"Attribute","startLoc":13,"text":"bp"},{"col":0,"comment":"","endLoc":1,"header":"blog.py#","id":966,"name":"","nodeType":"Function","startLoc":1,"text":"bp = Blueprint(\"blog\", __name__)"},{"col":0,"comment":"","endLoc":1,"header":"testing.py#","id":967,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n from .app import Flask\n from .wrappers import Response"},{"col":4,"comment":"null","endLoc":157,"header":"def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue","id":968,"name":"dispatch_request","nodeType":"Function","startLoc":148,"text":"def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:\n meth = getattr(self, request.method.lower(), None)\n\n # If the request method is HEAD and we don't have a handler for it\n # retry with GET.\n if meth is None and request.method == \"HEAD\":\n meth = getattr(self, \"get\", None)\n\n assert meth is not None, f\"Unimplemented method {request.method!r}\"\n return meth(*args, **kwargs)"},{"col":4,"comment":"null","endLoc":536,"header":"def _load_plugin_commands(self)","id":969,"name":"_load_plugin_commands","nodeType":"Function","startLoc":525,"text":"def _load_plugin_commands(self):\n if self._loaded_plugin_commands:\n return\n try:\n import pkg_resources\n except ImportError:\n self._loaded_plugin_commands = True\n return\n\n for ep in pkg_resources.iter_entry_points(\"flask.commands\"):\n self.add_command(ep.load(), ep.name)\n self._loaded_plugin_commands = True"},{"col":4,"comment":"null","endLoc":554,"header":"def get_command(self, ctx, name)","id":970,"name":"get_command","nodeType":"Function","startLoc":538,"text":"def get_command(self, ctx, name):\n self._load_plugin_commands()\n # Look up built-in and plugin commands, which should be\n # available even if the app fails to load.\n rv = super().get_command(ctx, name)\n\n if rv is not None:\n return rv\n\n info = ctx.ensure_object(ScriptInfo)\n\n # Look up commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n return info.load_app().cli.get_command(ctx, name)\n except NoAppException as e:\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")"},{"attributeType":"null","col":17,"comment":"null","endLoc":1,"id":971,"name":"t","nodeType":"Attribute","startLoc":1,"text":"t"},{"attributeType":"null","col":0,"comment":"null","endLoc":7,"id":972,"name":"http_method_funcs","nodeType":"Attribute","startLoc":7,"text":"http_method_funcs"},{"col":0,"comment":"","endLoc":1,"header":"views.py#","id":973,"name":"","nodeType":"Function","startLoc":1,"text":"http_method_funcs = frozenset(\n [\"get\", \"post\", \"head\", \"options\", \"delete\", \"put\", \"trace\", \"patch\"]\n)"},{"col":4,"comment":"null","endLoc":575,"header":"def list_commands(self, ctx)","id":974,"name":"list_commands","nodeType":"Function","startLoc":556,"text":"def list_commands(self, ctx):\n self._load_plugin_commands()\n # Start with the built-in and plugin commands.\n rv = set(super().list_commands(ctx))\n info = ctx.ensure_object(ScriptInfo)\n\n # Add commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n rv.update(info.load_app().cli.list_commands(ctx))\n except NoAppException as e:\n # When an app couldn't be loaded, show the error message\n # without the traceback.\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n except Exception:\n # When any other errors occurred during loading, show the\n # full traceback.\n click.secho(f\"{traceback.format_exc()}\\n\", err=True, fg=\"red\")\n\n return sorted(rv)"},{"col":4,"comment":"null","endLoc":596,"header":"def main(self, *args, **kwargs)","id":975,"name":"main","nodeType":"Function","startLoc":577,"text":"def main(self, *args, **kwargs):\n # Set a global flag that indicates that we were invoked from the\n # command line interface. This is detected by Flask.run to make the\n # call into a no-op. This is necessary to avoid ugly errors when the\n # script that is loaded here also attempts to start a server.\n os.environ[\"FLASK_RUN_FROM_CLI\"] = \"true\"\n\n if get_load_dotenv(self.load_dotenv):\n load_dotenv()\n\n obj = kwargs.get(\"obj\")\n\n if obj is None:\n obj = ScriptInfo(\n create_app=self.create_app, set_debug_flag=self.set_debug_flag\n )\n\n kwargs[\"obj\"] = obj\n kwargs.setdefault(\"auto_envvar_prefix\", \"FLASK\")\n return super().main(*args, **kwargs)"},{"attributeType":"null","col":8,"comment":"null","endLoc":515,"id":976,"name":"load_dotenv","nodeType":"Attribute","startLoc":515,"text":"self.load_dotenv"},{"attributeType":"null","col":8,"comment":"null","endLoc":523,"id":977,"name":"_loaded_plugin_commands","nodeType":"Attribute","startLoc":523,"text":"self._loaded_plugin_commands"},{"attributeType":"null","col":8,"comment":"null","endLoc":514,"id":978,"name":"create_app","nodeType":"Attribute","startLoc":514,"text":"self.create_app"},{"attributeType":"null","col":8,"comment":"null","endLoc":516,"id":979,"name":"set_debug_flag","nodeType":"Attribute","startLoc":516,"text":"self.set_debug_flag"},{"col":4,"comment":"null","endLoc":221,"header":"def open( # type: ignore\n self,\n *args: t.Any,\n as_tuple: bool = False,\n buffered: bool = False,\n follow_redirects: bool = False,\n **kwargs: t.Any,\n ) -> \"Response\"","id":980,"name":"open","nodeType":"Function","startLoc":174,"text":"def open( # type: ignore\n self,\n *args: t.Any,\n as_tuple: bool = False,\n buffered: bool = False,\n follow_redirects: bool = False,\n **kwargs: t.Any,\n ) -> \"Response\":\n # Same logic as super.open, but apply environ_base and preserve_context.\n request = None\n\n def copy_environ(other):\n return {\n **self.environ_base,\n **other,\n \"flask._preserve_context\": self.preserve_context,\n }\n\n if not kwargs and len(args) == 1:\n arg = args[0]\n\n if isinstance(arg, werkzeug.test.EnvironBuilder):\n builder = copy(arg)\n builder.environ_base = copy_environ(builder.environ_base or {})\n request = builder.get_request()\n elif isinstance(arg, dict):\n request = EnvironBuilder.from_environ(\n arg, app=self.application, environ_base=copy_environ({})\n ).get_request()\n elif isinstance(arg, BaseRequest):\n request = copy(arg)\n request.environ = copy_environ(request.environ)\n\n if request is None:\n kwargs[\"environ_base\"] = copy_environ(kwargs.get(\"environ_base\", {}))\n builder = EnvironBuilder(self.application, *args, **kwargs)\n\n try:\n request = builder.get_request()\n finally:\n builder.close()\n\n return super().open( # type: ignore\n request,\n as_tuple=as_tuple,\n buffered=buffered,\n follow_redirects=follow_redirects,\n )"},{"className":"CertParamType","col":0,"comment":"Click option type for the ``--cert`` option. Allows either an\n existing file, the string ``'adhoc'``, or an import for a\n :class:`~ssl.SSLContext` object.\n ","endLoc":733,"id":981,"nodeType":"Class","startLoc":692,"text":"class CertParamType(click.ParamType):\n \"\"\"Click option type for the ``--cert`` option. Allows either an\n existing file, the string ``'adhoc'``, or an import for a\n :class:`~ssl.SSLContext` object.\n \"\"\"\n\n name = \"path\"\n\n def __init__(self):\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n def convert(self, value, param, ctx):\n if ssl is None:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n )\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower()\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptography library.\",\n ctx,\n param,\n )\n\n return value\n\n obj = import_string(value, silent=True)\n\n if isinstance(obj, ssl.SSLContext):\n return obj\n\n raise"},{"col":4,"comment":"null","endLoc":701,"header":"def __init__(self)","id":982,"name":"__init__","nodeType":"Function","startLoc":700,"text":"def __init__(self):\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)"},{"col":4,"comment":"null","endLoc":733,"header":"def convert(self, value, param, ctx)","id":983,"name":"convert","nodeType":"Function","startLoc":703,"text":"def convert(self, value, param, ctx):\n if ssl is None:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n )\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower()\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptography library.\",\n ctx,\n param,\n )\n\n return value\n\n obj = import_string(value, silent=True)\n\n if isinstance(obj, ssl.SSLContext):\n return obj\n\n raise"},{"attributeType":"null","col":4,"comment":"null","endLoc":698,"id":985,"name":"name","nodeType":"Attribute","startLoc":698,"text":"name"},{"attributeType":"null","col":8,"comment":"null","endLoc":701,"id":986,"name":"path_type","nodeType":"Attribute","startLoc":701,"text":"self.path_type"},{"className":"SeparatedPathType","col":0,"comment":"Click option type that accepts a list of values separated by the\n OS's path separator (``:``, ``;`` on Windows). Each value is\n validated as a :class:`click.Path` type.\n ","endLoc":776,"id":987,"nodeType":"Class","startLoc":767,"text":"class SeparatedPathType(click.Path):\n \"\"\"Click option type that accepts a list of values separated by the\n OS's path separator (``:``, ``;`` on Windows). Each value is\n validated as a :class:`click.Path` type.\n \"\"\"\n\n def convert(self, value, param, ctx):\n items = self.split_envvar_value(value)\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]"},{"col":4,"comment":"null","endLoc":776,"header":"def convert(self, value, param, ctx)","id":988,"name":"convert","nodeType":"Function","startLoc":773,"text":"def convert(self, value, param, ctx):\n items = self.split_envvar_value(value)\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]"},{"col":0,"comment":"null","endLoc":291,"header":"def get_version(ctx, param, value)","id":989,"name":"get_version","nodeType":"Function","startLoc":278,"text":"def get_version(ctx, param, value):\n if not value or ctx.resilient_parsing:\n return\n\n import werkzeug\n from . import __version__\n\n click.echo(\n f\"Python {platform.python_version()}\\n\"\n f\"Flask {__version__}\\n\"\n f\"Werkzeug {werkzeug.__version__}\",\n color=ctx.color,\n )\n ctx.exit()"},{"col":0,"comment":"Take ``other`` and remove the length of ``path`` from it. Then join it\n to ``path``. If it is the original value, ``path`` is an ancestor of\n ``other``.","endLoc":603,"header":"def _path_is_ancestor(path, other)","id":990,"name":"_path_is_ancestor","nodeType":"Function","startLoc":599,"text":"def _path_is_ancestor(path, other):\n \"\"\"Take ``other`` and remove the length of ``path`` from it. Then join it\n to ``path``. If it is the original value, ``path`` is an ancestor of\n ``other``.\"\"\"\n return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other"},{"col":0,"comment":"The ``--key`` option must be specified when ``--cert`` is a file.\n Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.\n ","endLoc":764,"header":"def _validate_key(ctx, param, value)","id":991,"name":"_validate_key","nodeType":"Function","startLoc":736,"text":"def _validate_key(ctx, param, value):\n \"\"\"The ``--key`` option must be specified when ``--cert`` is a file.\n Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.\n \"\"\"\n cert = ctx.params.get(\"cert\")\n is_adhoc = cert == \"adhoc\"\n is_context = ssl and isinstance(cert, ssl.SSLContext)\n\n if value is not None:\n if is_adhoc:\n raise click.BadParameter(\n 'When \"--cert\" is \"adhoc\", \"--key\" is not used.', ctx, param\n )\n\n if is_context:\n raise click.BadParameter(\n 'When \"--cert\" is an SSLContext object, \"--key is not used.', ctx, param\n )\n\n if not cert:\n raise click.BadParameter('\"--cert\" must also be specified.', ctx, param)\n\n ctx.params[\"cert\"] = cert, value\n\n else:\n if cert and not (is_adhoc or is_context):\n raise click.BadParameter('Required when using \"--cert\".', ctx, param)\n\n return value"},{"col":4,"comment":"null","endLoc":227,"header":"def __enter__(self) -> \"FlaskClient\"","id":992,"name":"__enter__","nodeType":"Function","startLoc":223,"text":"def __enter__(self) -> \"FlaskClient\":\n if self.preserve_context:\n raise RuntimeError(\"Cannot nest client invocations\")\n self.preserve_context = True\n return self"},{"col":4,"comment":"null","endLoc":244,"header":"def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None","id":993,"name":"__exit__","nodeType":"Function","startLoc":229,"text":"def __exit__(\n self, exc_type: type, exc_value: BaseException, tb: TracebackType\n ) -> None:\n self.preserve_context = False\n\n # Normally the request context is preserved until the next\n # request in the same thread comes. When the client exits we\n # want to clean up earlier. Pop request contexts until the stack\n # is empty or a non-preserved one is found.\n while True:\n top = _request_ctx_stack.top\n\n if top is not None and top.preserved:\n top.pop()\n else:\n break"},{"col":0,"comment":"Run a local development server.\n\n This server is for development purposes only. It does not provide\n the stability, security, or performance of production WSGI servers.\n\n The reloader and debugger are enabled by default if\n FLASK_ENV=development or FLASK_DEBUG=1.\n ","endLoc":858,"header":"@click.command(\"run\", short_help=\"Run a development server.\")\n@click.option(\"--host\", \"-h\", default=\"127.0.0.1\", help=\"The interface to bind to.\")\n@click.option(\"--port\", \"-p\", default=5000, help=\"The port to bind to.\")\n@click.option(\n \"--cert\", type=CertParamType(), help=\"Specify a certificate file to use HTTPS.\"\n)\n@click.option(\n \"--key\",\n type=click.Path(exists=True, dir_okay=False, resolve_path=True),\n callback=_validate_key,\n expose_value=False,\n help=\"The key file to use when specifying a certificate.\",\n)\n@click.option(\n \"--reload/--no-reload\",\n default=None,\n help=\"Enable or disable the reloader. By default the reloader \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--debugger/--no-debugger\",\n default=None,\n help=\"Enable or disable the debugger. By default the debugger \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--eager-loading/--lazy-loading\",\n default=None,\n help=\"Enable or disable eager loading. By default eager \"\n \"loading is enabled if the reloader is disabled.\",\n)\n@click.option(\n \"--with-threads/--without-threads\",\n default=True,\n help=\"Enable or disable multithreading.\",\n)\n@click.option(\n \"--extra-files\",\n default=None,\n type=SeparatedPathType(),\n help=(\n \"Extra files that trigger a reload on change. Multiple paths\"\n f\" are separated by {os.path.pathsep!r}.\"\n ),\n)\n@pass_script_info\ndef run_command(\n info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files\n)","id":994,"name":"run_command","nodeType":"Function","startLoc":779,"text":"@click.command(\"run\", short_help=\"Run a development server.\")\n@click.option(\"--host\", \"-h\", default=\"127.0.0.1\", help=\"The interface to bind to.\")\n@click.option(\"--port\", \"-p\", default=5000, help=\"The port to bind to.\")\n@click.option(\n \"--cert\", type=CertParamType(), help=\"Specify a certificate file to use HTTPS.\"\n)\n@click.option(\n \"--key\",\n type=click.Path(exists=True, dir_okay=False, resolve_path=True),\n callback=_validate_key,\n expose_value=False,\n help=\"The key file to use when specifying a certificate.\",\n)\n@click.option(\n \"--reload/--no-reload\",\n default=None,\n help=\"Enable or disable the reloader. By default the reloader \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--debugger/--no-debugger\",\n default=None,\n help=\"Enable or disable the debugger. By default the debugger \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--eager-loading/--lazy-loading\",\n default=None,\n help=\"Enable or disable eager loading. By default eager \"\n \"loading is enabled if the reloader is disabled.\",\n)\n@click.option(\n \"--with-threads/--without-threads\",\n default=True,\n help=\"Enable or disable multithreading.\",\n)\n@click.option(\n \"--extra-files\",\n default=None,\n type=SeparatedPathType(),\n help=(\n \"Extra files that trigger a reload on change. Multiple paths\"\n f\" are separated by {os.path.pathsep!r}.\"\n ),\n)\n@pass_script_info\ndef run_command(\n info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files\n):\n \"\"\"Run a local development server.\n\n This server is for development purposes only. It does not provide\n the stability, security, or performance of production WSGI servers.\n\n The reloader and debugger are enabled by default if\n FLASK_ENV=development or FLASK_DEBUG=1.\n \"\"\"\n debug = get_debug_flag()\n\n if reload is None:\n reload = debug\n\n if debugger is None:\n debugger = debug\n\n show_server_banner(get_env(), debug, info.app_import_path, eager_loading)\n app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)\n\n from werkzeug.serving import run_simple\n\n run_simple(\n host,\n port,\n app,\n use_reloader=reload,\n use_debugger=debugger,\n threaded=with_threads,\n ssl_context=cert,\n extra_files=extra_files,\n )"},{"attributeType":"Flask","col":4,"comment":"null","endLoc":109,"id":995,"name":"application","nodeType":"Attribute","startLoc":109,"text":"application"},{"attributeType":"null","col":4,"comment":"null","endLoc":110,"id":996,"name":"preserve_context","nodeType":"Attribute","startLoc":110,"text":"preserve_context"},{"attributeType":"null","col":8,"comment":"null","endLoc":114,"id":997,"name":"environ_base","nodeType":"Attribute","startLoc":114,"text":"self.environ_base"},{"attributeType":"null","col":8,"comment":"null","endLoc":226,"id":998,"name":"preserve_context","nodeType":"Attribute","startLoc":226,"text":"self.preserve_context"},{"col":0,"comment":"null","endLoc":98,"header":"def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]","id":999,"name":"_make_timedelta","nodeType":"Function","startLoc":94,"text":"def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:\n if value is None or isinstance(value, timedelta):\n return value\n\n return timedelta(seconds=value)"},{"attributeType":"null","col":4,"comment":"null","endLoc":81,"id":1000,"name":"iscoroutinefunction","nodeType":"Attribute","startLoc":81,"text":"iscoroutinefunction"},{"col":0,"comment":"","endLoc":1,"header":"app.py#","id":1001,"name":"","nodeType":"Function","startLoc":1,"text":"if t.TYPE_CHECKING:\n import typing_extensions as te\n from .blueprints import Blueprint\n from .testing import FlaskClient\n from .testing import FlaskCliRunner\n\nif sys.version_info >= (3, 8):\n iscoroutinefunction = inspect.iscoroutinefunction\nelse:\n\n def iscoroutinefunction(func: t.Any) -> bool:\n while inspect.ismethod(func):\n func = func.__func__\n\n while isinstance(func, functools.partial):\n func = func.func\n\n return inspect.iscoroutinefunction(func)"},{"col":0,"comment":"Run an interactive Python shell in the context of a given\n Flask application. The application will populate the default\n namespace of this shell according to its configuration.\n\n This is useful for executing small snippets of management code\n without having to manually configure the application.\n ","endLoc":909,"header":"@click.command(\"shell\", short_help=\"Run a shell in the app context.\")\n@with_appcontext\ndef shell_command() -> None","id":1002,"name":"shell_command","nodeType":"Function","startLoc":861,"text":"@click.command(\"shell\", short_help=\"Run a shell in the app context.\")\n@with_appcontext\ndef shell_command() -> None:\n \"\"\"Run an interactive Python shell in the context of a given\n Flask application. The application will populate the default\n namespace of this shell according to its configuration.\n\n This is useful for executing small snippets of management code\n without having to manually configure the application.\n \"\"\"\n import code\n from .globals import _app_ctx_stack\n\n app = _app_ctx_stack.top.app\n banner = (\n f\"Python {sys.version} on {sys.platform}\\n\"\n f\"App: {app.import_name} [{app.env}]\\n\"\n f\"Instance: {app.instance_path}\"\n )\n ctx: dict = {}\n\n # Support the regular Python interpreter startup script if someone\n # is using it.\n startup = os.environ.get(\"PYTHONSTARTUP\")\n if startup and os.path.isfile(startup):\n with open(startup) as f:\n eval(compile(f.read(), startup, \"exec\"), ctx)\n\n ctx.update(app.make_shell_context())\n\n # Site, customize, or startup script can set a hook to call when\n # entering interactive mode. The default one sets up readline with\n # tab and history completion.\n interactive_hook = getattr(sys, \"__interactivehook__\", None)\n\n if interactive_hook is not None:\n try:\n import readline\n from rlcompleter import Completer\n except ImportError:\n pass\n else:\n # rlcompleter uses __main__.__dict__ by default, which is\n # flask.__main__. Use the shell context instead.\n readline.set_completer(Completer(ctx).complete)\n\n interactive_hook()\n\n code.interact(banner=banner, local=ctx)"},{"col":0,"comment":"Show all registered routes with endpoints and methods.","endLoc":958,"header":"@click.command(\"routes\", short_help=\"Show the routes for the app.\")\n@click.option(\n \"--sort\",\n \"-s\",\n type=click.Choice((\"endpoint\", \"methods\", \"rule\", \"match\")),\n default=\"endpoint\",\n help=(\n 'Method to sort routes by. \"match\" is the order that Flask will match '\n \"routes when dispatching a request.\"\n ),\n)\n@click.option(\"--all-methods\", is_flag=True, help=\"Show HEAD and OPTIONS methods.\")\n@with_appcontext\ndef routes_command(sort","id":1003,"name":"routes_command","nodeType":"Function","startLoc":912,"text":"@click.command(\"routes\", short_help=\"Show the routes for the app.\")\n@click.option(\n \"--sort\",\n \"-s\",\n type=click.Choice((\"endpoint\", \"methods\", \"rule\", \"match\")),\n default=\"endpoint\",\n help=(\n 'Method to sort routes by. \"match\" is the order that Flask will match '\n \"routes when dispatching a request.\"\n ),\n)\n@click.option(\"--all-methods\", is_flag=True, help=\"Show HEAD and OPTIONS methods.\")\n@with_appcontext\ndef routes_command(sort: str, all_methods: bool) -> None:\n \"\"\"Show all registered routes with endpoints and methods.\"\"\"\n\n rules = list(current_app.url_map.iter_rules())\n if not rules:\n click.echo(\"No routes were registered.\")\n return\n\n ignored_methods = set(() if all_methods else (\"HEAD\", \"OPTIONS\"))\n\n if sort in (\"endpoint\", \"rule\"):\n rules = sorted(rules, key=attrgetter(sort))\n elif sort == \"methods\":\n rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore\n\n rule_methods = [\n \", \".join(sorted(rule.methods - ignored_methods)) # type: ignore\n for rule in rules\n ]\n\n headers = (\"Endpoint\", \"Methods\", \"Rule\")\n widths = (\n max(len(rule.endpoint) for rule in rules),\n max(len(methods) for methods in rule_methods),\n max(len(rule.rule) for rule in rules),\n )\n widths = [max(len(h), w) for h, w in zip(headers, widths)]\n row = \"{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}\".format(*widths)\n\n click.echo(row.format(*headers).strip())\n click.echo(row.format(*(\"-\" * width for width in widths)))\n\n for rule, methods in zip(rules, rule_methods):\n click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())"},{"col":34,"endLoc":938,"id":1004,"nodeType":"Lambda","startLoc":938,"text":"lambda rule: sorted(rule.methods)"},{"attributeType":"null","col":0,"comment":"null","endLoc":294,"id":1005,"name":"version_option","nodeType":"Attribute","startLoc":294,"text":"version_option"},{"attributeType":"null","col":0,"comment":"null","endLoc":427,"id":1006,"name":"pass_script_info","nodeType":"Attribute","startLoc":427,"text":"pass_script_info"},{"attributeType":"FlaskGroup","col":0,"comment":"null","endLoc":961,"id":1007,"name":"cli","nodeType":"Attribute","startLoc":961,"text":"cli"},{"col":0,"comment":"","endLoc":1,"header":"cli.py#","id":1008,"name":"","nodeType":"Function","startLoc":1,"text":"try:\n import dotenv\nexcept ImportError:\n dotenv = None\n\ntry:\n import ssl\nexcept ImportError:\n ssl = None # type: ignore\n\nversion_option = click.Option(\n [\"--version\"],\n help=\"Show the flask version\",\n expose_value=False,\n callback=get_version,\n is_flag=True,\n is_eager=True,\n)\n\npass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)\n\ncli = FlaskGroup(\n help=\"\"\"\\\nA general utility script for Flask applications.\n\nProvides commands from Flask, extensions, and the application. Loads the\napplication defined in the FLASK_APP environment variable, or from a wsgi.py\nfile. Setting the FLASK_ENV environment variable to 'development' will enable\ndebug mode.\n\n\\b\n {prefix}{cmd} FLASK_APP=hello.py\n {prefix}{cmd} FLASK_ENV=development\n {prefix}flask run\n\"\"\".format(\n cmd=\"export\" if os.name == \"posix\" else \"set\",\n prefix=\"$ \" if os.name == \"posix\" else \"> \",\n )\n)\n\nif __name__ == \"__main__\":\n main()"}]} \ No newline at end of file