diff --git a/chapter8/Vagrantfile b/chapter8/Vagrantfile new file mode 100644 index 0000000..26ed1cd --- /dev/null +++ b/chapter8/Vagrantfile @@ -0,0 +1,40 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + +Vagrant.require_version ">= 1.6.0" + +boxes = [ + { + :name => "docker-ee-manager", + :eth1 => "192.168.205.50", + :mem => "3072", + :cpu => "1" + }, + { + :name => "docker-ee-worker", + :eth1 => "192.168.205.60", + :mem => "3072", + :cpu => "1" + } + +] + +Vagrant.configure(2) do |config| + + config.vm.box = "centos/7" + boxes.each do |opts| + config.vm.define opts[:name] do |config| + config.vm.hostname = opts[:name] + config.vm.provider "vmware_fusion" do |v| + v.vmx["memsize"] = opts[:mem] + v.vmx["numvcpus"] = opts[:cpu] + end + config.vm.provider "virtualbox" do |v| + v.customize ["modifyvm", :id, "--memory", opts[:mem]] + v.customize ["modifyvm", :id, "--cpus", opts[:cpu]] + end + config.vm.network :private_network, ip: opts[:eth1] + end + end + config.vm.synced_folder "./labs", "/home/vagrant/labs" +end diff --git a/chapter8/labs/flask-skeleton/.coveragerc b/chapter8/labs/flask-skeleton/.coveragerc new file mode 100644 index 0000000..2f39d7a --- /dev/null +++ b/chapter8/labs/flask-skeleton/.coveragerc @@ -0,0 +1,16 @@ +[run] +source = skeleton +omit = + skeleton/tests/* + */__init__.py + +[report] +exclude_lines = + def __repr__ + def __str__ + def parse_args + pragma: no cover + raise NotImplementedError + if __name__ == .__main__.: + +ignore_errors = True diff --git a/chapter8/labs/flask-skeleton/.gitignore b/chapter8/labs/flask-skeleton/.gitignore new file mode 100644 index 0000000..3cf10dd --- /dev/null +++ b/chapter8/labs/flask-skeleton/.gitignore @@ -0,0 +1,91 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +*.sqlite diff --git a/chapter8/labs/flask-skeleton/.gitlab-ci.yml b/chapter8/labs/flask-skeleton/.gitlab-ci.yml new file mode 100644 index 0000000..7450601 --- /dev/null +++ b/chapter8/labs/flask-skeleton/.gitlab-ci.yml @@ -0,0 +1,62 @@ +variables: + GIT_SSL_NO_VERIFY: "1" + +stages: + - test + - build + - deploy + +pep8: + stage: test + image: python:2.7 + script: + - pip install tox + - tox -e pep8 + tags: + - python27 + +unittest-py27: + stage: test + image: python:2.7 + script: + - pip install tox + - tox -e py27 + tags: + - python27 + +unittest-py34: + stage: test + image: python:3.4 + script: + - pip install tox + - tox -e py34 + tags: + - python34 + +sphnix: + stage: test + image: python:2.7 + script: + - pip install tox + - tox -e docs + tags: + - python27 + +build: + stage: build + tags: + - shell + script: + - docker build -t skeleton . + only: + - master + +deploy: + stage: deploy + tags: + - shell + script: + - scripts/deploy.sh + - export + only: + - master diff --git a/chapter8/labs/flask-skeleton/CONTRIBUTING.md b/chapter8/labs/flask-skeleton/CONTRIBUTING.md new file mode 100644 index 0000000..bdf68e1 --- /dev/null +++ b/chapter8/labs/flask-skeleton/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Hacking Guide + +## Code style + +Step 1: Read http://www.python.org/dev/peps/pep-0008/ + +Step 2: Read http://www.python.org/dev/peps/pep-0008/ again + +Step 3: Read on + +## Running Tests + +Run tox + +``` +$ cd skeleton +$ tox +``` diff --git a/chapter8/labs/flask-skeleton/Dockerfile b/chapter8/labs/flask-skeleton/Dockerfile new file mode 100644 index 0000000..689c89b --- /dev/null +++ b/chapter8/labs/flask-skeleton/Dockerfile @@ -0,0 +1,9 @@ +FROM python:2.7 + +MAINTAINER Peng Xiao + +COPY . /skeleton +WORKDIR /skeleton +RUN pip install -r requirements.txt +EXPOSE 5050 +ENTRYPOINT ["scripts/dev.sh"] diff --git a/chapter8/labs/flask-skeleton/LICENSE b/chapter8/labs/flask-skeleton/LICENSE new file mode 100644 index 0000000..b100feb --- /dev/null +++ b/chapter8/labs/flask-skeleton/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2016 Michael Herman + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/chapter8/labs/flask-skeleton/README.md b/chapter8/labs/flask-skeleton/README.md new file mode 100644 index 0000000..3a53d09 --- /dev/null +++ b/chapter8/labs/flask-skeleton/README.md @@ -0,0 +1,58 @@ +[![build status](https://gitlab-demo.com/Demo/flask-skeleton/badges/master/build.svg)](https://gitlab-demo.com/Demo/flask-skeleton/commits/master) +[![coverage report](https://gitlab-demo.com/Demo/flask-skeleton/badges/master/coverage.svg)](https://gitlab-demo.com/Demo/flask-skeleton/commits/master) + + +# Flask Skeleton + +Flask starter project... + +## Quick Start + +### Basics + +1. Activate a virtualenv +1. Install the requirements + +### Set Environment Variables + +Update *skeleton/server/config.py*, and then run: + +```sh +$ export APP_SETTINGS="skeleton.server.config.DevelopmentConfig" +``` + +or + +```sh +$ export APP_SETTINGS="skeleton.server.config.ProductionConfig" +``` + +### Create DB + +```sh +$ python manage.py create_db +$ python manage.py db init +$ python manage.py db migrate +$ python manage.py create_admin +$ python manage.py create_data +``` + +### Run the Application + +```sh +$ python manage.py runserver +``` + +So access the application at the address [http://localhost:5000/](http://localhost:5000/) + +> Want to specify a different port? + +> ```sh +> $ python manage.py runserver -h 0.0.0.0 -p 8080 +> ``` + +### Testing1 + +``` +$ tox +``` diff --git a/chapter8/labs/flask-skeleton/doc/Makefile b/chapter8/labs/flask-skeleton/doc/Makefile new file mode 100644 index 0000000..e93e305 --- /dev/null +++ b/chapter8/labs/flask-skeleton/doc/Makefile @@ -0,0 +1,225 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " epub3 to make an epub3" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + @echo " dummy to check syntax errors of document sources" + +.PHONY: clean +clean: + rm -rf $(BUILDDIR)/* + +.PHONY: html +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +.PHONY: dirhtml +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +.PHONY: singlehtml +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +.PHONY: pickle +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +.PHONY: json +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +.PHONY: htmlhelp +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +.PHONY: qthelp +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/yacore.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/yacore.qhc" + +.PHONY: applehelp +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +.PHONY: devhelp +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/yacore" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/yacore" + @echo "# devhelp" + +.PHONY: epub +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +.PHONY: epub3 +epub3: + $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 + @echo + @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." + +.PHONY: latex +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +.PHONY: latexpdf +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: latexpdfja +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: text +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +.PHONY: man +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +.PHONY: texinfo +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +.PHONY: info +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +.PHONY: gettext +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +.PHONY: changes +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +.PHONY: linkcheck +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +.PHONY: doctest +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +.PHONY: coverage +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +.PHONY: xml +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +.PHONY: pseudoxml +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." + +.PHONY: dummy +dummy: + $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy + @echo + @echo "Build finished. Dummy builder generates no files." diff --git a/chapter8/labs/flask-skeleton/doc/make.bat b/chapter8/labs/flask-skeleton/doc/make.bat new file mode 100644 index 0000000..f82584c --- /dev/null +++ b/chapter8/labs/flask-skeleton/doc/make.bat @@ -0,0 +1,281 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source +set I18NSPHINXOPTS=%SPHINXOPTS% source +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. epub3 to make an epub3 + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + echo. coverage to run coverage check of the documentation if enabled + echo. dummy to check syntax errors of document sources + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +REM Check if sphinx-build is available and fallback to Python version if any +%SPHINXBUILD% 1>NUL 2>NUL +if errorlevel 9009 goto sphinx_python +goto sphinx_ok + +:sphinx_python + +set SPHINXBUILD=python -m sphinx.__init__ +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +:sphinx_ok + + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\yacore.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\yacore.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "epub3" ( + %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "coverage" ( + %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage + if errorlevel 1 exit /b 1 + echo. + echo.Testing of coverage in the sources finished, look at the ^ +results in %BUILDDIR%/coverage/python.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +if "%1" == "dummy" ( + %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. Dummy builder generates no files. + goto end +) + +:end diff --git a/chapter8/labs/flask-skeleton/doc/source/_static/.placeholder b/chapter8/labs/flask-skeleton/doc/source/_static/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/doc/source/_templates/.placeholder b/chapter8/labs/flask-skeleton/doc/source/_templates/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/doc/source/conf.py b/chapter8/labs/flask-skeleton/doc/source/conf.py new file mode 100644 index 0000000..04526ef --- /dev/null +++ b/chapter8/labs/flask-skeleton/doc/source/conf.py @@ -0,0 +1,342 @@ +# -*- coding: utf-8 -*- +# +# skeleton documentation build configuration file, created by +# sphinx-quickstart on Mon Aug 1 21:41:36 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'skeleton' +copyright = u'2016, Peng Xiao' +author = u'Peng Xiao' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'1.0' +# The full version, including alpha/beta/rc tags. +release = u'1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'alabaster' +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = u'skeleton v1.0' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'skeletondoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'skeleton.tex', u'skeleton Documentation', + u'Peng Xiao', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# +# latex_use_parts = False + +# If true, show page references after internal links. +# +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# +# latex_appendices = [] + +# It false, will not define \strong, \code, itleref, \crossref ... but only +# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added +# packages. +# +# latex_keep_old_macro_names = True + +# If false, no module index is generated. +# +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'skeleton', u'skeleton Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +# +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'skeleton', u'skeleton Documentation', + author, 'skeleton', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# +# texinfo_appendices = [] + +# If false, no module index is generated. +# +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# +# texinfo_no_detailmenu = False diff --git a/chapter8/labs/flask-skeleton/doc/source/index.rst b/chapter8/labs/flask-skeleton/doc/source/index.rst new file mode 100644 index 0000000..0193c98 --- /dev/null +++ b/chapter8/labs/flask-skeleton/doc/source/index.rst @@ -0,0 +1,25 @@ +.. yacore documentation master file, created by + sphinx-quickstart on Mon Aug 1 21:41:36 2016. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to yacore's documentation! +================================== + +This is a test line +test again +test +Contents: + +.. toctree:: + :maxdepth: 2 + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/chapter8/labs/flask-skeleton/manage.py b/chapter8/labs/flask-skeleton/manage.py new file mode 100644 index 0000000..b443e69 --- /dev/null +++ b/chapter8/labs/flask-skeleton/manage.py @@ -0,0 +1,56 @@ +# manage.py + +import unittest + +from flask_script import Manager +from flask_migrate import Migrate, MigrateCommand + +from skeleton.server import app, db +from skeleton.server.models import User + + +migrate = Migrate(app, db) +manager = Manager(app) + +# migrations +manager.add_command('db', MigrateCommand) + + +@manager.command +def test(): + """Runs the unit tests without coverage.""" + tests = unittest.TestLoader().discover('tests', pattern='test*.py') + result = unittest.TextTestRunner(verbosity=2).run(tests) + if result.wasSuccessful(): + return 0 + else: + return 1 + + +@manager.command +def create_db(): + """Creates the db tables.""" + db.create_all() + + +@manager.command +def drop_db(): + """Drops the db tables.""" + db.drop_all() + + +@manager.command +def create_admin(): + """Creates the admin user.""" + db.session.add(User(email='admin@cisco.com', password='admin', admin=True)) + db.session.commit() + + +@manager.command +def create_data(): + """Creates sample data.""" + pass + + +if __name__ == '__main__': + manager.run() diff --git a/chapter8/labs/flask-skeleton/migrations/README b/chapter8/labs/flask-skeleton/migrations/README new file mode 100755 index 0000000..98e4f9c --- /dev/null +++ b/chapter8/labs/flask-skeleton/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/chapter8/labs/flask-skeleton/migrations/alembic.ini b/chapter8/labs/flask-skeleton/migrations/alembic.ini new file mode 100644 index 0000000..f8ed480 --- /dev/null +++ b/chapter8/labs/flask-skeleton/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/chapter8/labs/flask-skeleton/migrations/env.py b/chapter8/labs/flask-skeleton/migrations/env.py new file mode 100755 index 0000000..4593816 --- /dev/null +++ b/chapter8/labs/flask-skeleton/migrations/env.py @@ -0,0 +1,87 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import fileConfig +import logging + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +from flask import current_app +config.set_main_option('sqlalchemy.url', + current_app.config.get('SQLALCHEMY_DATABASE_URI')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.readthedocs.org/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + engine = engine_from_config(config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure(connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/chapter8/labs/flask-skeleton/migrations/script.py.mako b/chapter8/labs/flask-skeleton/migrations/script.py.mako new file mode 100755 index 0000000..9570201 --- /dev/null +++ b/chapter8/labs/flask-skeleton/migrations/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision} +Create Date: ${create_date} + +""" + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/chapter8/labs/flask-skeleton/requirements.txt b/chapter8/labs/flask-skeleton/requirements.txt new file mode 100644 index 0000000..32c7949 --- /dev/null +++ b/chapter8/labs/flask-skeleton/requirements.txt @@ -0,0 +1,26 @@ +alembic==0.8.6 +bcrypt==3.1.0 +blinker==1.4 +cffi==1.7.0 +click==6.6 +dominate==2.2.1 +Flask==0.10.1 +Flask-Bcrypt==0.7.1 +Flask-Bootstrap==3.3.6.0 +Flask-DebugToolbar==0.10.0 +Flask-Login==0.3.2 +Flask-Migrate==1.8.1 +Flask-Script==2.0.5 +Flask-SQLAlchemy==2.1 +Flask-WTF==0.12 +itsdangerous==0.24 +Jinja2==2.8 +Mako==1.0.4 +MarkupSafe==0.23 +pycparser==2.14 +python-editor==1.0.1 +six==1.10.0 +SQLAlchemy==1.0.14 +visitor==0.1.3 +Werkzeug==0.11.10 +WTForms==2.1 diff --git a/chapter8/labs/flask-skeleton/scripts/deploy.sh b/chapter8/labs/flask-skeleton/scripts/deploy.sh new file mode 100755 index 0000000..009ff05 --- /dev/null +++ b/chapter8/labs/flask-skeleton/scripts/deploy.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +docker ps -a | grep penxiao_skeleton | awk '{print$1}' | xargs docker stop +docker ps -a | grep penxiao_skeleton | awk '{print$1}' | xargs docker rm +docker run -d -p 80:5000 --name penxiao_skeleton skeleton diff --git a/chapter8/labs/flask-skeleton/scripts/dev.sh b/chapter8/labs/flask-skeleton/scripts/dev.sh new file mode 100755 index 0000000..eaf9c73 --- /dev/null +++ b/chapter8/labs/flask-skeleton/scripts/dev.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +export APP_SETTINGS="skeleton.server.config.ProductionConfig" +python manage.py create_db +python manage.py create_admin +python manage.py create_data +python manage.py runserver -h 0.0.0.0 diff --git a/chapter8/labs/flask-skeleton/skeleton/__init__.py b/chapter8/labs/flask-skeleton/skeleton/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/skeleton/client/static/main.css b/chapter8/labs/flask-skeleton/skeleton/client/static/main.css new file mode 100644 index 0000000..3ec203c --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/static/main.css @@ -0,0 +1,5 @@ +/* custom css */ + +.site-content { + padding-top: 75px; +} \ No newline at end of file diff --git a/chapter8/labs/flask-skeleton/skeleton/client/static/main.js b/chapter8/labs/flask-skeleton/skeleton/client/static/main.js new file mode 100644 index 0000000..f0a356f --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/static/main.js @@ -0,0 +1,5 @@ +// custom javascript + +$( document ).ready(function() { + console.log('Sanity Check!'); +}); \ No newline at end of file diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/_base.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/_base.html new file mode 100644 index 0000000..cad8115 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/_base.html @@ -0,0 +1,66 @@ + + + + + + Flask Skeleton{% block title %}{% endblock %} + + + + + + + + {% block css %}{% endblock %} + + + + + {% include 'header.html' %} + +
+
+ + + {% with messages = get_flashed_messages(with_categories=true) %} + {% if messages %} +
+
+
+ {% for category, message in messages %} +
+ × + {{message}} +
+ {% endfor %} +
+
+ {% endif %} + {% endwith %} + + + + {% block content %}{% endblock %} + +
+ + + {% if error %} +

Error: {{ error }}

+ {% endif %} + +
+
+ +

+ + {% include 'footer.html' %} + + + + + + {% block js %}{% endblock %} + + + diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/401.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/401.html new file mode 100644 index 0000000..3b8875c --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/401.html @@ -0,0 +1,12 @@ +{% extends "_base.html" %} + +{% block page_title %}- Unauthorized{% endblock %} + +{% block content %} +
+
+

401

+

You are not authorized to view this page. Please log in.

+
+
+{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/403.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/403.html new file mode 100644 index 0000000..3b8875c --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/403.html @@ -0,0 +1,12 @@ +{% extends "_base.html" %} + +{% block page_title %}- Unauthorized{% endblock %} + +{% block content %} +
+
+

401

+

You are not authorized to view this page. Please log in.

+
+
+{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/404.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/404.html new file mode 100644 index 0000000..39e7767 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/404.html @@ -0,0 +1,12 @@ +{% extends "_base.html" %} + +{% block page_title %}- Page Not Found{% endblock %} + +{% block content %} +
+
+

404

+

Sorry. The requested page doesn't exist. Go home.

+
+
+{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/500.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/500.html new file mode 100644 index 0000000..4bedc21 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/errors/500.html @@ -0,0 +1,12 @@ +{% extends "_base.html" %} + +{% block page_title %}- Server Error{% endblock %} + +{% block content %} +
+
+

500

+

Sorry. Something went terribly wrong. Go home.

+
+
+{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/footer.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/footer.html new file mode 100644 index 0000000..18d0ace --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/footer.html @@ -0,0 +1,7 @@ + diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/header.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/header.html new file mode 100644 index 0000000..4f7ec8b --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/header.html @@ -0,0 +1,35 @@ + \ No newline at end of file diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/main/about.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/main/about.html new file mode 100644 index 0000000..7f781e7 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/main/about.html @@ -0,0 +1,11 @@ +{% extends "_base.html" %} + +{% block content %} + +
+
+

About

+
+
+ +{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/main/home.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/main/home.html new file mode 100644 index 0000000..2bd944a --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/main/home.html @@ -0,0 +1,11 @@ +{% extends "_base.html" %} + +{% block content %} + +
+
+

Welcome!

+
+
+ +{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/user/login.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/login.html new file mode 100644 index 0000000..c1123e9 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/login.html @@ -0,0 +1,33 @@ +{% extends '_base.html' %} +{% import "bootstrap/wtf.html" as wtf %} + +{% block content %} + +
+

Please login

+
+ +
+ + +
+ + {{ form.csrf_token }} + {{ form.hidden_tag() }} + {{ wtf.form_errors(form, hiddens="only") }} + + +
+ + {{ wtf.form_field(form.email) }} + {{ wtf.form_field(form.password) }} + + +

+

Need to Register?

+
+ +
+ + +{% endblock content %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/user/members.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/members.html new file mode 100644 index 0000000..d790995 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/members.html @@ -0,0 +1,5 @@ +{% extends "_base.html" %} +{% block content %} +

Welcome, {{ current_user.email }}!

+

This is the members-only page :)

+{% endblock %} diff --git a/chapter8/labs/flask-skeleton/skeleton/client/templates/user/register.html b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/register.html new file mode 100644 index 0000000..c3d884c --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/client/templates/user/register.html @@ -0,0 +1,35 @@ +{% extends '_base.html' %} +{% import "bootstrap/wtf.html" as wtf %} + +{% block content %} + +
+

Please Register

+
+ +
+ + +
+ + {{ form.csrf_token }} + {{ form.hidden_tag() }} + {{ wtf.form_errors(form, hiddens="only") }} + + +
+ + {{ wtf.form_field(form.email) }} + {{ wtf.form_field(form.password) }} + {{ wtf.form_field(form.confirm) }} + + +

+

Already have an account? Sign in.

+ +
+ +
+ + +{% endblock content %} diff --git a/chapter8/labs/flask-skeleton/skeleton/server/__init__.py b/chapter8/labs/flask-skeleton/skeleton/server/__init__.py new file mode 100644 index 0000000..b35b6b7 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/__init__.py @@ -0,0 +1,63 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import os + +from flask import Flask, render_template +from flask_login import LoginManager +from flask_bcrypt import Bcrypt +from flask_debugtoolbar import DebugToolbarExtension +from flask_bootstrap import Bootstrap +from flask_sqlalchemy import SQLAlchemy + + +app = Flask( + __name__, + template_folder='../client/templates', + static_folder='../client/static' +) + +app_settings = os.getenv('APP_SETTINGS', 'skeleton.server.config.DevelopmentConfig') +app.config.from_object(app_settings) + +login_manager = LoginManager() +login_manager.init_app(app) +bcrypt = Bcrypt(app) +toolbar = DebugToolbarExtension(app) +bootstrap = Bootstrap(app) +db = SQLAlchemy(app) + +from skeleton.server.user.views import user_blueprint +from skeleton.server.main.views import main_blueprint +app.register_blueprint(user_blueprint) +app.register_blueprint(main_blueprint) + +from skeleton.server.models import User + +login_manager.login_view = "user.login" +login_manager.login_message_category = 'danger' + + +@login_manager.user_loader +def load_user(user_id): + return User.query.filter(User.id == int(user_id)).first() + + +@app.errorhandler(401) +def forbidden_page_401(error): + return render_template("errors/401.html"), 401 + + +@app.errorhandler(403) +def forbidden_page_403(error): + return render_template("errors/403.html"), 403 + + +@app.errorhandler(404) +def page_not_found(error): + return render_template("errors/404.html"), 404 + + +@app.errorhandler(500) +def server_error_page(error): + return render_template("errors/500.html"), 500 diff --git a/chapter8/labs/flask-skeleton/skeleton/server/config.py b/chapter8/labs/flask-skeleton/skeleton/server/config.py new file mode 100644 index 0000000..823847d --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/config.py @@ -0,0 +1,43 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import os +basedir = os.path.abspath(os.path.dirname(__file__)) + + +class BaseConfig(object): + """Base configuration.""" + SECRET_KEY = 'my_precious' + DEBUG = False + BCRYPT_LOG_ROUNDS = 13 + WTF_CSRF_ENABLED = True + DEBUG_TB_ENABLED = False + DEBUG_TB_INTERCEPT_REDIRECTS = False + SQLALCHEMY_TRACK_MODIFICATIONS = False + SQLALCHEMY_DATABASE_URI = os.environ.get( + 'DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'db.sqlite')) + + +class DevelopmentConfig(BaseConfig): + """Development configuration.""" + DEBUG = True + BCRYPT_LOG_ROUNDS = 4 + WTF_CSRF_ENABLED = False + DEBUG_TB_ENABLED = True + + +class TestingConfig(BaseConfig): + """Testing configuration.""" + DEBUG = True + TESTING = True + BCRYPT_LOG_ROUNDS = 4 + WTF_CSRF_ENABLED = False + DEBUG_TB_ENABLED = False + PRESERVE_CONTEXT_ON_EXCEPTION = False + + +class ProductionConfig(BaseConfig): + """Production configuration.""" + SECRET_KEY = 'my_precious' + DEBUG = False + DEBUG_TB_ENABLED = False diff --git a/chapter8/labs/flask-skeleton/skeleton/server/main/__init__.py b/chapter8/labs/flask-skeleton/skeleton/server/main/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/skeleton/server/main/views.py b/chapter8/labs/flask-skeleton/skeleton/server/main/views.py new file mode 100644 index 0000000..3c0385a --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/main/views.py @@ -0,0 +1,16 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +from flask import render_template, Blueprint + +main_blueprint = Blueprint('main', __name__,) + + +@main_blueprint.route('/') +def home(): + return render_template('main/home.html') + + +@main_blueprint.route("/about/") +def about(): + return render_template("main/about.html") diff --git a/chapter8/labs/flask-skeleton/skeleton/server/models.py b/chapter8/labs/flask-skeleton/skeleton/server/models.py new file mode 100644 index 0000000..6db5a6d --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/models.py @@ -0,0 +1,40 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import datetime + +from skeleton.server import app, db, bcrypt + + +class User(db.Model): + + __tablename__ = "users" + + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + email = db.Column(db.String(255), unique=True, nullable=False) + password = db.Column(db.String(255), nullable=False) + registered_on = db.Column(db.DateTime, nullable=False) + admin = db.Column(db.Boolean, nullable=False, default=False) + + def __init__(self, email, password, admin=False): + self.email = email + self.password = bcrypt.generate_password_hash( + password, app.config.get('BCRYPT_LOG_ROUNDS') + ) + self.registered_on = datetime.datetime.now() + self.admin = admin + + def is_authenticated(self): + return True + + def is_active(self): + return True + + def is_anonymous(self): + return False + + def get_id(self): + return self.id + + def __repr__(self): + return ''.format(self.email) diff --git a/chapter8/labs/flask-skeleton/skeleton/server/user/__init__.py b/chapter8/labs/flask-skeleton/skeleton/server/user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/skeleton/server/user/forms.py b/chapter8/labs/flask-skeleton/skeleton/server/user/forms.py new file mode 100644 index 0000000..e7c6c47 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/user/forms.py @@ -0,0 +1,28 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +from flask_wtf import Form +from wtforms import StringField, PasswordField +from wtforms.validators import DataRequired, Email, Length, EqualTo + + +class LoginForm(Form): + email = StringField('Email Address', [DataRequired(), Email()]) + password = PasswordField('Password', [DataRequired()]) + + +class RegisterForm(Form): + email = StringField( + 'Email Address', + validators=[DataRequired(), Email(message=None), Length(min=6, max=40)]) + password = PasswordField( + 'Password', + validators=[DataRequired(), Length(min=6, max=25)] + ) + confirm = PasswordField( + 'Confirm password', + validators=[ + DataRequired(), + EqualTo('password', message='Passwords must match.') + ] + ) diff --git a/chapter8/labs/flask-skeleton/skeleton/server/user/views.py b/chapter8/labs/flask-skeleton/skeleton/server/user/views.py new file mode 100644 index 0000000..a2ab408 --- /dev/null +++ b/chapter8/labs/flask-skeleton/skeleton/server/user/views.py @@ -0,0 +1,62 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + + +from flask import render_template, Blueprint, url_for, \ + redirect, flash, request +from flask_login import login_user, logout_user, login_required + +from skeleton.server import bcrypt, db +from skeleton.server.models import User +from skeleton.server.user.forms import LoginForm, RegisterForm + +user_blueprint = Blueprint('user', __name__,) + + +@user_blueprint.route('/register', methods=['GET', 'POST']) +def register(): + form = RegisterForm(request.form) + if form.validate_on_submit(): + user = User( + email=form.email.data, + password=form.password.data + ) + db.session.add(user) + db.session.commit() + + login_user(user) + + flash('Thank you for registering.', 'success') + return redirect(url_for("user.members")) + + return render_template('user/register.html', form=form) + + +@user_blueprint.route('/login', methods=['GET', 'POST']) +def login(): + form = LoginForm(request.form) + if form.validate_on_submit(): + user = User.query.filter_by(email=form.email.data).first() + if user and bcrypt.check_password_hash( + user.password, request.form['password']): + login_user(user) + flash('You are logged in. Welcome!', 'success') + return redirect(url_for('user.members')) + else: + flash('Invalid email and/or password.', 'danger') + return render_template('user/login.html', form=form) + return render_template('user/login.html', title='Please Login', form=form) + + +@user_blueprint.route('/logout') +@login_required +def logout(): + logout_user() + flash('You were logged out. Bye!', 'success') + return redirect(url_for('main.home')) + + +@user_blueprint.route('/members') +@login_required +def members(): + return render_template('user/members.html') diff --git a/chapter8/labs/flask-skeleton/test-requirements.txt b/chapter8/labs/flask-skeleton/test-requirements.txt new file mode 100644 index 0000000..9da57fd --- /dev/null +++ b/chapter8/labs/flask-skeleton/test-requirements.txt @@ -0,0 +1,5 @@ +flake8==2.4.0 +Flask-Testing==0.4.2 +discover +nose +coverage==4.0.3 diff --git a/chapter8/labs/flask-skeleton/tests/__init__.py b/chapter8/labs/flask-skeleton/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chapter8/labs/flask-skeleton/tests/base.py b/chapter8/labs/flask-skeleton/tests/base.py new file mode 100644 index 0000000..2411f85 --- /dev/null +++ b/chapter8/labs/flask-skeleton/tests/base.py @@ -0,0 +1,24 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +from flask_testing import TestCase + +from skeleton.server import app, db +from skeleton.server.models import User + + +class BaseTestCase(TestCase): + + def create_app(self): + app.config.from_object('skeleton.server.config.TestingConfig') + return app + + def setUp(self): + db.create_all() + user = User(email="ad@min.com", password="admin_user") + db.session.add(user) + db.session.commit() + + def tearDown(self): + db.session.remove() + db.drop_all() diff --git a/chapter8/labs/flask-skeleton/tests/test_config.py b/chapter8/labs/flask-skeleton/tests/test_config.py new file mode 100644 index 0000000..87f875d --- /dev/null +++ b/chapter8/labs/flask-skeleton/tests/test_config.py @@ -0,0 +1,54 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import unittest + +from flask import current_app +from flask_testing import TestCase + +from skeleton.server import app + + +class TestDevelopmentConfig(TestCase): + + def create_app(self): + app.config.from_object('skeleton.server.config.DevelopmentConfig') + return app + + def test_app_is_development(self): + # self.assertFalse(current_app.config['TESTING']) + self.assertTrue(app.config['DEBUG'] is True) + self.assertTrue(app.config['WTF_CSRF_ENABLED'] is False) + self.assertTrue(app.config['DEBUG_TB_ENABLED'] is True) + self.assertFalse(current_app is None) + + +class TestTestingConfig(TestCase): + + def create_app(self): + app.config.from_object('skeleton.server.config.TestingConfig') + return app + + def test_app_is_testing(self): + self.assertTrue(current_app.config['TESTING']) + self.assertTrue(app.config['DEBUG'] is True) + self.assertTrue(app.config['BCRYPT_LOG_ROUNDS'] == 4) + self.assertTrue(app.config['WTF_CSRF_ENABLED'] is False) + + +class TestProductionConfig(TestCase): + + def create_app(self): + app.config.from_object('skeleton.server.config.ProductionConfig') + return app + + def test_app_is_production(self): + # self.assertFalse(current_app.config['TESTING']) + self.assertTrue(app.config['DEBUG'] is False) + self.assertTrue(app.config['DEBUG_TB_ENABLED'] is False) + self.assertTrue(app.config['WTF_CSRF_ENABLED'] is True) + self.assertTrue(app.config['BCRYPT_LOG_ROUNDS'] == 13) + + +if __name__ == '__main__': + unittest.main() diff --git a/chapter8/labs/flask-skeleton/tests/test_main.py b/chapter8/labs/flask-skeleton/tests/test_main.py new file mode 100644 index 0000000..2af8eee --- /dev/null +++ b/chapter8/labs/flask-skeleton/tests/test_main.py @@ -0,0 +1,37 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import unittest + +from base import BaseTestCase + + +class TestMainBlueprint(BaseTestCase): + + def test_index(self): + # Ensure Flask is setup. + response = self.client.get('/', follow_redirects=True) + self.assertEqual(response.status_code, 200) + self.assertIn(b'Welcome!', response.data) + self.assertIn(b'Register/Login', response.data) + + def test_footer(self): + response = self.client.get('/', follow_redirects=True) + self.assertEqual(response.status_code, 200) + self.assertIn(b'GitLab Demo', response.data) + + def test_about(self): + # Ensure about route behaves correctly. + response = self.client.get('/about', follow_redirects=True) + self.assertEqual(response.status_code, 200) + self.assertIn(b'About', response.data) + + def test_404(self): + # Ensure 404 error is handled. + response = self.client.get('/404') + self.assert404(response) + self.assertTemplateUsed('errors/404.html') + + +if __name__ == '__main__': + unittest.main() diff --git a/chapter8/labs/flask-skeleton/tests/test_user.py b/chapter8/labs/flask-skeleton/tests/test_user.py new file mode 100644 index 0000000..2479549 --- /dev/null +++ b/chapter8/labs/flask-skeleton/tests/test_user.py @@ -0,0 +1,116 @@ +# Copyright 2016 Cisco Systems, Inc. +# All rights reserved. + +import datetime +import unittest + +from flask_login import current_user + +from base import BaseTestCase +from skeleton.server import bcrypt +from skeleton.server.models import User +from skeleton.server.user.forms import LoginForm + + +class TestUserBlueprint(BaseTestCase): + + def test_correct_login(self): + # Ensure login behaves correctly with correct credentials. + with self.client: + response = self.client.post( + '/login', + data=dict(email="ad@min.com", password="admin_user"), + follow_redirects=True + ) + self.assertIn(b'Welcome', response.data) + self.assertIn(b'Logout', response.data) + self.assertIn(b'Members', response.data) + self.assertTrue(current_user.email == "ad@min.com") + self.assertTrue(current_user.is_active()) + self.assertEqual(response.status_code, 200) + + def test_logout_behaves_correctly(self): + # Ensure logout behaves correctly - regarding the session. + with self.client: + self.client.post( + '/login', + data=dict(email="ad@min.com", password="admin_user"), + follow_redirects=True + ) + response = self.client.get('/logout', follow_redirects=True) + self.assertIn(b'You were logged out. Bye!', response.data) + self.assertFalse(current_user.is_active) + + def test_logout_route_requires_login(self): + # Ensure logout route requres logged in user. + response = self.client.get('/logout', follow_redirects=True) + self.assertIn(b'Please log in to access this page', response.data) + + def test_member_route_requires_login(self): + # Ensure member route requres logged in user. + response = self.client.get('/members', follow_redirects=True) + self.assertIn(b'Please log in to access this page', response.data) + + def test_validate_success_login_form(self): + # Ensure correct data validates. + form = LoginForm(email='ad@min.com', password='admin_user') + self.assertTrue(form.validate()) + + def test_validate_invalid_email_format(self): + # Ensure invalid email format throws error. + form = LoginForm(email='unknown', password='example') + self.assertFalse(form.validate()) + + def test_get_by_id(self): + # Ensure id is correct for the current/logged in user. + with self.client: + self.client.post('/login', data=dict( + email='ad@min.com', password='admin_user' + ), follow_redirects=True) + self.assertTrue(current_user.id == 1) + + def test_registered_on_defaults_to_datetime(self): + # Ensure that registered_on is a datetime. + with self.client: + self.client.post('/login', data=dict( + email='ad@min.com', password='admin_user' + ), follow_redirects=True) + user = User.query.filter_by(email='ad@min.com').first() + self.assertIsInstance(user.registered_on, datetime.datetime) + + def test_check_password(self): + # Ensure given password is correct after unhashing. + user = User.query.filter_by(email='ad@min.com').first() + self.assertTrue(bcrypt.check_password_hash(user.password, 'admin_user')) + self.assertFalse(bcrypt.check_password_hash(user.password, 'foobar')) + + def test_validate_invalid_password(self): + # Ensure user can't login when the pasword is incorrect. + with self.client: + response = self.client.post('/login', data=dict( + email='ad@min.com', password='foo_bar' + ), follow_redirects=True) + self.assertIn(b'Invalid email and/or password.', response.data) + + def test_register_route(self): + # Ensure about route behaves correctly. + response = self.client.get('/register', follow_redirects=True) + self.assertIn(b'

Please Register

\n', response.data) + + def test_user_registration(self): + # Ensure registration behaves correctlys. + with self.client: + response = self.client.post( + '/register', + data=dict(email="test@tester.com", password="testing", + confirm="testing"), + follow_redirects=True + ) + self.assertIn(b'Welcome', response.data) + self.assertTrue(current_user.email == "test@tester.com") + self.assertTrue(current_user.is_active()) + self.assertEqual(response.status_code, 200) + + +if __name__ == '__main__': + unittest.main() diff --git a/chapter8/labs/flask-skeleton/tox.ini b/chapter8/labs/flask-skeleton/tox.ini new file mode 100644 index 0000000..d73b6b8 --- /dev/null +++ b/chapter8/labs/flask-skeleton/tox.ini @@ -0,0 +1,58 @@ +# Tox (http://tox.testrun.org/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +# List the environment that will be run by default +minversion = 1.6 +envlist = py27, py34, pep8, docs +skipsdist = True + +[testenv] +setenv = VIRTUAL_ENV={envdir} + LANG=en_US.UTF-8 + LANGUAGE=en_US:en + LC_ALL=C + +[testenv:py27] +deps = -r{toxinidir}/test-requirements.txt + -r{toxinidir}/requirements.txt + + +commands = + coverage run manage.py test + coverage report -m + +[testenv:py34] +deps = -r{toxinidir}/test-requirements.txt + -r{toxinidir}/requirements.txt + +commands = + coverage run manage.py test + coverage report -m + +[testenv:pep8] +sitepackages = False +deps = -r{toxinidir}/test-requirements.txt +commands = + flake8 {posargs} + +[flake8] +# E712 is ignored on purpose, since it is normal to use 'column == true' +# in sqlalchemy. +# H803 skipped on purpose per list discussion. +# E125 is deliberately excluded. See https://github.com/jcrocholl/pep8/issues/126 +# The rest of the ignores are TODOs +# New from hacking 0.9: E129, E131, E265, E713, H407, H405, H904 +# Stricter in hacking 0.9: F402 +# E251 Skipped due to https://github.com/jcrocholl/pep8/issues/301 + +max-line-length=120 +exclude = .venv,.git,.tox,dist,doc,*lib/python*,*egg,build,tools + +[testenv:docs] +deps= + sphinx + sphinx_rtd_theme +commands = sphinx-build -W -b html doc/source doc/build diff --git "a/\345\270\270\350\247\201\351\227\256\351\242\230\346\261\207\346\200\273.md" "b/\345\270\270\350\247\201\351\227\256\351\242\230\346\261\207\346\200\273.md" new file mode 100644 index 0000000..ce6135d --- /dev/null +++ "b/\345\270\270\350\247\201\351\227\256\351\242\230\346\261\207\346\200\273.md" @@ -0,0 +1,28 @@ +欢迎大家添加 + +# Vagrant启动失败,Virtualbox版本不支持? + +目前Vagrant只支持VirtualBox versions 4.0.x, 4.1.x, 4.2.x, 4.3.x, 5.0.x, 5.1.x, and 5.2.x. 其它版本不支持,大家的virtualbox如果不是这几个版本,请卸载重新安装 + +# Docker的镜像加速 + +如果大家感觉在我们的Vagrant 机器里下载docker image速度很慢或者干脆访问失败,则可以设置镜像加速,使用国内的镜像加速,方法如下: + +请在 /etc/docker/daemon.json 中写入如下内容(如果文件不存在请新建该文件) + +``` +{ + "registry-mirrors": [ + "https://registry.docker-cn.com" + ] +} +``` +注意,一定要保证该文件符合 json 规范,否则 Docker 将不能启动。 + +之后重新启动服务。 + +``` +$ sudo systemctl daemon-reload +$ sudo systemctl restart docker +``` +