github.com/grafana/pyroscope@v1.18.0/tools/api-docs-generator/python.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 9 "github.com/getkin/kin-openapi/openapi3" 10 ) 11 12 type pythonExpr string 13 14 func (e pythonExpr) MarshalJSON() ([]byte, error) { //nolint:unparam 15 return []byte(`"#` + string(e) + `#"`), nil 16 } 17 18 type examplePython struct { 19 sc *openapi3.Schema 20 } 21 22 func newExamplePython(sc *openapi3.Schema) *examplePython { 23 return &examplePython{sc: sc} 24 } 25 26 func (e *examplePython) name() string { 27 return "python" 28 } 29 30 func (e *examplePython) render(sb io.Writer, params *exampleParams) { 31 body := map[string]any{} 32 collectParameters(e.sc, "", func(prefix string, name string, schema *openapi3.Schema) { 33 exStr, exValue := getExample(schema) 34 if exStr == "" { 35 return 36 } 37 38 ex, ok := exampleParameters[exStr] 39 if !ok || ex.Python == nil { 40 setBody(body, prefix, name, exValue) 41 return 42 } 43 44 setBody(body, prefix, name, ex.Python) 45 }) 46 47 addLabelsToSeries(body, "__name__", "process_cpu") 48 bodyJson, err := json.MarshalIndent(&body, " ", " ") 49 if err != nil { 50 panic(err) 51 } 52 // convert commands so they are run in python 53 bodyJson = bytes.ReplaceAll(bodyJson, []byte{'#', '"'}, []byte{}) 54 bodyJson = bytes.ReplaceAll(bodyJson, []byte{'"', '#'}, []byte{}) 55 56 fmt.Fprintln(sb, "import requests") 57 if bytes.Contains(bodyJson, []byte("datetime")) { 58 fmt.Fprintln(sb, "import datetime") 59 } 60 if bytes.Contains(bodyJson, []byte("base64")) { 61 fmt.Fprintln(sb, "import base64") 62 } 63 fmt.Fprintf(sb, "body = %s\n", string(bodyJson)) 64 fmt.Fprintf(sb, "url = '%s'\n", params.url) 65 fmt.Fprintln(sb, "resp = requests.post(url, json=body)") 66 fmt.Fprintln(sb, "print(resp)") 67 fmt.Fprintln(sb, "print(resp.content)") 68 }