github.com/devcamcar/cli@v0.0.0-20181107134215-706a05759d18/langs/python.go (about) 1 package langs 2 3 import ( 4 "errors" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 ) 10 11 type PythonLangHelper struct { 12 BaseHelper 13 Version string 14 } 15 16 func (h *PythonLangHelper) DefaultFormat() string { 17 return "http-stream" 18 } 19 20 func (h *PythonLangHelper) HasBoilerplate() bool { return true } 21 22 func (h *PythonLangHelper) GenerateBoilerplate(path string) error { 23 codeFile := filepath.Join(path, "func.py") 24 if exists(codeFile) { 25 return errors.New("func.py already exists, canceling init") 26 } 27 if err := ioutil.WriteFile(codeFile, []byte(helloPythonSrcBoilerplate), os.FileMode(0644)); err != nil { 28 return err 29 } 30 depFile := "requirements.txt" 31 if err := ioutil.WriteFile(depFile, []byte(reqsPythonSrcBoilerplate), os.FileMode(0644)); err != nil { 32 return err 33 } 34 35 return nil 36 } 37 38 func (h *PythonLangHelper) Handles(lang string) bool { 39 return defaultHandles(h, lang) 40 } 41 func (h *PythonLangHelper) Runtime() string { 42 return h.LangStrings()[0] 43 } 44 45 func (h *PythonLangHelper) LangStrings() []string { 46 return []string{"python", fmt.Sprintf("python%s", h.Version)} 47 } 48 49 func (h *PythonLangHelper) Extensions() []string { 50 return []string{".py"} 51 } 52 53 func (h *PythonLangHelper) BuildFromImage() (string, error) { 54 return fmt.Sprintf("fnproject/python:%s-dev", h.Version), nil 55 } 56 57 func (h *PythonLangHelper) RunFromImage() (string, error) { 58 return fmt.Sprintf("fnproject/python:%s", h.Version), nil 59 } 60 61 func (h *PythonLangHelper) Entrypoint() (string, error) { 62 return "python3 func.py", nil 63 } 64 65 func (h *PythonLangHelper) DockerfileBuildCmds() []string { 66 r := []string{} 67 r = append(r, "ADD . /function/") 68 if exists("requirements.txt") { 69 r = append(r, ` 70 RUN pip3 install --target /python/ --no-cache --no-cache-dir -r requirements.txt &&\ 71 rm -fr ~/.cache/pip /tmp* requirements.txt func.yaml Dockerfile .venv`) 72 } 73 return r 74 } 75 76 func (h *PythonLangHelper) IsMultiStage() bool { 77 return true 78 } 79 80 const ( 81 helloPythonSrcBoilerplate = `import fdk 82 import json 83 84 85 def handler(ctx, data=None, loop=None): 86 name = "World" 87 if data and len(data) > 0: 88 body = json.loads(data) 89 name = body.get("name") 90 return {"message": "Hello {0}".format(name)} 91 92 93 if __name__ == "__main__": 94 fdk.handle(handler) 95 96 ` 97 reqsPythonSrcBoilerplate = `fdk` 98 ) 99 100 func (h *PythonLangHelper) DockerfileCopyCmds() []string { 101 return []string{ 102 "COPY --from=build-stage /function /function", 103 "COPY --from=build-stage /python /python", 104 "ENV PYTHONPATH=/python", 105 } 106 }