{{ post['title'] }}
16 |{{ post['body'] }}
23 |├── .gitignore ├── LICENSE ├── README.md ├── azure-pipelines.yml ├── basic-unittest.md ├── django-basic.yml ├── django-basic ├── azure-pipelines.yml ├── azuredemo │ ├── azuredemo │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── demo │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── manage.py ├── pytest.ini └── requirements.txt ├── django-multi-environment ├── azure-pipelines.yml ├── azuredemo │ ├── azuredemo │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── demo │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── manage.py └── pytest.ini ├── flask-basic ├── LICENSE ├── MANIFEST.in ├── README.rst ├── azure-pipelines.yml ├── flaskr │ ├── __init__.py │ ├── auth.py │ ├── blog.py │ ├── db.py │ ├── schema.sql │ ├── static │ │ └── style.css │ └── templates │ │ ├── auth │ │ ├── login.html │ │ └── register.html │ │ ├── base.html │ │ └── blog │ │ ├── create.html │ │ ├── index.html │ │ └── update.html ├── setup.cfg ├── setup.py └── tests │ ├── conftest.py │ ├── data.sql │ ├── test_auth.py │ ├── test_blog.py │ ├── test_db.py │ └── test_factory.py ├── library-basic ├── azure-pipelines.yml ├── demolib │ ├── __init__.py │ └── code.py ├── requirements.txt ├── setup.py └── tests │ └── test_code.py └── library-flit ├── README.md ├── azure-pipelines.yml ├── demolib ├── __init__.py └── code.py ├── pyproject.toml └── tests └── test_code.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | **/venv/ 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Anthony Shaw 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # azure-pipelines-python-examples 2 | Example configurations for Azure Build Pipelines for Python 3 | 4 | [](https://dev.azure.com/AnthonyShaw/azure-pipelines-python-examples/_build/latest?definitionId=2?branchName=master) 5 | 6 | * [A Django 2.1 project, tested on Python 3.6 and 3.7](django-basic) 7 | * [A Django 2.1 project, tested on Python 3.6 and 3.7, but against 2 versions of Django (2.1.3 and 2.1.4)](django-multi-environment) 8 | * [A Flask project, tested on Python 3.6 and Python 3.7](flask-basic) 9 | * [A Python library with a wheel and source distribution](library-basic) 10 | * [A Python library built with flit and pyproject.toml](library-flit) 11 | 12 | The full detail on these is on [my blog](https://medium.com/@anthonypjshaw/azure-pipelines-with-python-by-example-aa65f4070634) 13 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | - master 3 | name: $(Date:yyyyMMdd)$(Rev:.r) 4 | 5 | jobs: 6 | - template: 'django-basic/azure-pipelines.yml' 7 | - template: 'django-multi-environment/azure-pipelines.yml' 8 | - template: 'flask-basic/azure-pipelines.yml' 9 | - template: 'library-basic/azure-pipelines.yml' 10 | - template: 'library-flit/azure-pipelines.yml' 11 | -------------------------------------------------------------------------------- /basic-unittest.md: -------------------------------------------------------------------------------- 1 | # Basic Python Windows + Linux example 2 | 3 | This example uses nose2 as the test runner with the junit XML plugin. This is passed to Azure pipelines so the test output is cleanly parsed. 4 | 5 | Also, this example assumes: 6 | - Python 3.6 and 3.7 (change Matrix for Linux + Windows to alter) 7 | - Your tests are in a directory called "tests" (change the nose2 line to alter) 8 | 9 | ```yaml 10 | trigger: 11 | - master 12 | 13 | jobs: 14 | 15 | - job: 'Test_Linux' 16 | pool: 17 | vmImage: 'Ubuntu-16.04' 18 | strategy: 19 | matrix: 20 | Python36: 21 | python.version: '3.6' 22 | Python37: 23 | python.version: '3.7' 24 | maxParallel: 2 25 | 26 | steps: 27 | - task: UsePythonVersion@0 28 | inputs: 29 | versionSpec: '$(python.version)' 30 | architecture: 'x64' 31 | 32 | - script: | 33 | python -m pip install --upgrade pip 34 | pip install -r requirements.txt 35 | displayName: 'Install dependencies' 36 | 37 | - script: | 38 | pip install nose2 39 | nose2 --plugin nose2.plugins.junitxml --junit-xml tests 40 | displayName: 'Run tests' 41 | 42 | - task: PublishTestResults@2 43 | inputs: 44 | testResultsFiles: '**/nose2-junit.xml' 45 | testRunTitle: 'Python $(python.version)' 46 | condition: succeededOrFailed() 47 | 48 | - job: 'Test_Windows' 49 | pool: 50 | vmImage: 'vs2017-win2016' 51 | strategy: 52 | matrix: 53 | Python36: 54 | python.version: '3.6' 55 | Python37: 56 | python.version: '3.7' 57 | maxParallel: 2 58 | 59 | steps: 60 | - task: UsePythonVersion@0 61 | inputs: 62 | versionSpec: '$(python.version)' 63 | architecture: 'x64' 64 | 65 | - script: | 66 | python -m pip install --upgrade pip 67 | pip install -r requirements.txt 68 | displayName: 'Install dependencies' 69 | 70 | - script: | 71 | pip install nose2 72 | nose2 --plugin nose2.plugins.junitxml --junit-xml tests 73 | displayName: 'Run tests' 74 | 75 | - task: PublishTestResults@2 76 | inputs: 77 | testResultsFiles: '**\nose2-junit.xml' 78 | testRunTitle: 'Python $(python.version)' 79 | condition: succeededOrFailed() 80 | 81 | ``` 82 | -------------------------------------------------------------------------------- /django-basic.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | - master 3 | 4 | jobs: 5 | 6 | - job: 'django_basic' 7 | pool: 8 | vmImage: 'Ubuntu-16.04' 9 | strategy: 10 | matrix: 11 | Python36: 12 | python.version: '3.6' 13 | Python37: 14 | python.version: '3.7' 15 | maxParallel: 2 16 | 17 | steps: 18 | - task: UsePythonVersion@0 19 | inputs: 20 | versionSpec: '$(python.version)' 21 | architecture: 'x64' 22 | 23 | - script: | 24 | python -m pip install --upgrade pip 25 | pip install -r django-basic/requirements.txt 26 | displayName: 'Install dependencies' 27 | - script: | 28 | pip install pytest-django 29 | cd django-basic/azuredemo 30 | pytest --junitxml=../../reports/django-basic.xml 31 | displayName: 'Run tests' 32 | - task: PublishTestResults@2 33 | inputs: 34 | testResultsFiles: 'reports/django-basic.xml' 35 | testRunTitle: '$(Agent.OS) - $(Build.DefinitionName) - Python $(python.version)' 36 | condition: succeededOrFailed() 37 | -------------------------------------------------------------------------------- /django-basic/azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # To use this pipeline standalone, uncomment the `trigger` 2 | # and `name` stanzas. As-is, the pipeline is suitable for 3 | # importing as a template 4 | # 5 | # trigger: 6 | # - master 7 | # name: $(Date:yyyyMMdd)$(Rev:.r) 8 | jobs: 9 | 10 | - job: 'django_basic' 11 | pool: 12 | vmImage: 'Ubuntu-16.04' 13 | strategy: 14 | matrix: 15 | Python36: 16 | python.version: '3.6' 17 | Python37: 18 | python.version: '3.7' 19 | maxParallel: 2 20 | 21 | steps: 22 | - task: UsePythonVersion@0 23 | inputs: 24 | versionSpec: '$(python.version)' 25 | architecture: 'x64' 26 | 27 | - script: | 28 | python -m pip install --upgrade pip 29 | pip install -r django-basic/requirements.txt 30 | displayName: 'Install dependencies' 31 | 32 | - script: | 33 | pip install pytest-django 34 | cd django-basic/azuredemo 35 | pytest --junitxml=../../reports/django-basic.xml 36 | displayName: 'Run tests' 37 | 38 | - task: PublishTestResults@2 39 | inputs: 40 | testResultsFiles: 'reports/django-basic.xml' 41 | testRunTitle: '$(Agent.OS) - $(Build.BuildNumber)[$(Agent.JobName)] - Python $(python.version)' 42 | condition: succeededOrFailed() 43 | -------------------------------------------------------------------------------- /django-basic/azuredemo/azuredemo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-basic/azuredemo/azuredemo/__init__.py -------------------------------------------------------------------------------- /django-basic/azuredemo/azuredemo/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for azuredemo project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'e@(*h5w1g!4^@0%8(yf8o2dyw96lj9sa8in%41q891_88peg99' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | ] 51 | 52 | ROOT_URLCONF = 'azuredemo.urls' 53 | 54 | TEMPLATES = [ 55 | { 56 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 57 | 'DIRS': [], 58 | 'APP_DIRS': True, 59 | 'OPTIONS': { 60 | 'context_processors': [ 61 | 'django.template.context_processors.debug', 62 | 'django.template.context_processors.request', 63 | 'django.contrib.auth.context_processors.auth', 64 | 'django.contrib.messages.context_processors.messages', 65 | ], 66 | }, 67 | }, 68 | ] 69 | 70 | WSGI_APPLICATION = 'azuredemo.wsgi.application' 71 | 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 75 | 76 | DATABASES = { 77 | 'default': { 78 | 'ENGINE': 'django.db.backends.sqlite3', 79 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 80 | } 81 | } 82 | 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | 103 | # Internationalization 104 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 105 | 106 | LANGUAGE_CODE = 'en-us' 107 | 108 | TIME_ZONE = 'UTC' 109 | 110 | USE_I18N = True 111 | 112 | USE_L10N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 119 | 120 | STATIC_URL = '/static/' 121 | -------------------------------------------------------------------------------- /django-basic/azuredemo/azuredemo/urls.py: -------------------------------------------------------------------------------- 1 | """azuredemo URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('demo/', include('demo.urls')) 22 | ] 23 | -------------------------------------------------------------------------------- /django-basic/azuredemo/azuredemo/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for azuredemo project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azuredemo.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-basic/azuredemo/demo/__init__.py -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DemoConfig(AppConfig): 5 | name = 'demo' 6 | -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-basic/azuredemo/demo/migrations/__init__.py -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase, Client 2 | 3 | class DemoTestCase(TestCase): 4 | def test_index_no_user(self): 5 | c = Client() 6 | response = c.post('/demo/', {'person': None}) 7 | assert response.status_code == 404 8 | 9 | def test_index_ground_control(self): 10 | c = Client() 11 | response = c.post('/demo/', {'person': 'ground_control', 'message': 'Ground Control to Major Tom'}) 12 | assert response.status_code == 200 13 | assert 'the stars look very different today' in response.content.decode('utf-8') 14 | -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('', views.index, name='index'), 8 | ] -------------------------------------------------------------------------------- /django-basic/azuredemo/demo/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse, Http404 3 | 4 | # Create your views here. 5 | def index(request): 6 | if 'person' in request.POST: 7 | if request.POST['person'] == 'ground_control' \ 8 | and request.POST['message'] == 'Ground Control to Major Tom': 9 | return HttpResponse( 10 | """
This is Major Tom to Ground Control, 11 | I'm stepping through the door, 12 | And I'm floating in a most peculiar way, 13 | And the stars look very different today.
""") 14 | raise Http404("Huh?") 15 | -------------------------------------------------------------------------------- /django-basic/azuredemo/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azuredemo.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /django-basic/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | python_files = tests.py test_*.py *_tests.py 3 | DJANGO_SETTINGS_MODULE = azuredemo.settings 4 | -------------------------------------------------------------------------------- /django-basic/requirements.txt: -------------------------------------------------------------------------------- 1 | Django==3.2.20 2 | pytz==2018.7 3 | -------------------------------------------------------------------------------- /django-multi-environment/azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # To use this pipeline standalone, uncomment the `trigger` 2 | # and `name` stanzas. As-is, the pipeline is suitable for 3 | # importing as a template 4 | # 5 | # trigger: 6 | # - master 7 | # name: $(Date:yyyyMMdd)$(Rev:.r) 8 | jobs: 9 | 10 | - job: 'django_multi_environment' 11 | pool: 12 | vmImage: 'Ubuntu-16.04' 13 | strategy: 14 | matrix: 15 | Python36_Django213: 16 | python.version: '3.6' 17 | django.version: '2.1.3' 18 | Python37_Django213: 19 | python.version: '3.7' 20 | django.version: '2.1.3' 21 | Python37_Django214: 22 | python.version: '3.7' 23 | django.version: '2.1.4' 24 | maxParallel: 3 25 | 26 | steps: 27 | - task: UsePythonVersion@0 28 | inputs: 29 | versionSpec: '$(python.version)' 30 | architecture: 'x64' 31 | 32 | - script: | 33 | python -m pip install --upgrade pip 34 | pip install django==$(django.version) 35 | displayName: 'Install dependencies' 36 | 37 | - script: | 38 | pip install pytest-django 39 | cd django-multi-environment/azuredemo 40 | pytest --junitxml=../../reports/django-multi-environment.xml 41 | displayName: 'Run tests' 42 | 43 | - task: PublishTestResults@2 44 | inputs: 45 | testResultsFiles: 'reports/django-multi-environment.xml' 46 | testRunTitle: '$(Agent.OS) - $(Build.BuildNumber)[$(Agent.JobName)] - Python $(python.version) - Django $(django.version)' 47 | condition: succeededOrFailed() 48 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/azuredemo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-multi-environment/azuredemo/azuredemo/__init__.py -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/azuredemo/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for azuredemo project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'e@(*h5w1g!4^@0%8(yf8o2dyw96lj9sa8in%41q891_88peg99' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | ] 51 | 52 | ROOT_URLCONF = 'azuredemo.urls' 53 | 54 | TEMPLATES = [ 55 | { 56 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 57 | 'DIRS': [], 58 | 'APP_DIRS': True, 59 | 'OPTIONS': { 60 | 'context_processors': [ 61 | 'django.template.context_processors.debug', 62 | 'django.template.context_processors.request', 63 | 'django.contrib.auth.context_processors.auth', 64 | 'django.contrib.messages.context_processors.messages', 65 | ], 66 | }, 67 | }, 68 | ] 69 | 70 | WSGI_APPLICATION = 'azuredemo.wsgi.application' 71 | 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 75 | 76 | DATABASES = { 77 | 'default': { 78 | 'ENGINE': 'django.db.backends.sqlite3', 79 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 80 | } 81 | } 82 | 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | 103 | # Internationalization 104 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 105 | 106 | LANGUAGE_CODE = 'en-us' 107 | 108 | TIME_ZONE = 'UTC' 109 | 110 | USE_I18N = True 111 | 112 | USE_L10N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 119 | 120 | STATIC_URL = '/static/' 121 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/azuredemo/urls.py: -------------------------------------------------------------------------------- 1 | """azuredemo URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('demo/', include('demo.urls')) 22 | ] 23 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/azuredemo/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for azuredemo project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azuredemo.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-multi-environment/azuredemo/demo/__init__.py -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DemoConfig(AppConfig): 5 | name = 'demo' 6 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tonybaloney/azure-pipelines-python-examples/820b53bcd75fff1aa112a66cdf03ff476dad4e0a/django-multi-environment/azuredemo/demo/migrations/__init__.py -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase, Client 2 | 3 | class DemoTestCase(TestCase): 4 | def test_index_no_user(self): 5 | c = Client() 6 | response = c.post('/demo/', {'person': None}) 7 | assert response.status_code == 404 8 | 9 | def test_index_ground_control(self): 10 | c = Client() 11 | response = c.post('/demo/', {'person': 'ground_control', 'message': 'Ground Control to Major Tom'}) 12 | assert response.status_code == 200 13 | assert 'the stars look very different today' in response.content.decode('utf-8') 14 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | 4 | from . import views 5 | 6 | urlpatterns = [ 7 | path('', views.index, name='index'), 8 | ] -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/demo/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse, Http404 3 | 4 | # Create your views here. 5 | def index(request): 6 | if 'person' in request.POST: 7 | if request.POST['person'] == 'ground_control' \ 8 | and request.POST['message'] == 'Ground Control to Major Tom': 9 | return HttpResponse( 10 | """This is Major Tom to Ground Control, 11 | I'm stepping through the door, 12 | And I'm floating in a most peculiar way, 13 | And the stars look very different today.
""") 14 | raise Http404("Huh?") 15 | -------------------------------------------------------------------------------- /django-multi-environment/azuredemo/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azuredemo.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /django-multi-environment/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | python_files = tests.py test_*.py *_tests.py 3 | DJANGO_SETTINGS_MODULE = azuredemo.settings 4 | -------------------------------------------------------------------------------- /flask-basic/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright © 2010 by the Pallets team. 2 | 3 | Some rights reserved. 4 | 5 | Redistribution and use in source and binary forms of the software as 6 | well as documentation, with or without modification, are permitted 7 | provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | * Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND 21 | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 22 | BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 23 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 24 | COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 26 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 27 | USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 28 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 30 | THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /flask-basic/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include flaskr/schema.sql 3 | graft flaskr/static 4 | graft flaskr/templates 5 | graft tests 6 | global-exclude *.pyc 7 | -------------------------------------------------------------------------------- /flask-basic/README.rst: -------------------------------------------------------------------------------- 1 | Flaskr 2 | ====== 3 | 4 | The basic blog app built in the Flask `tutorial`_. 5 | 6 | .. _tutorial: http://flask.pocoo.org/docs/tutorial/ 7 | 8 | 9 | Install 10 | ------- 11 | 12 | **Be sure to use the same version of the code as the version of the docs 13 | you're reading.** You probably want the latest tagged version, but the 14 | default Git version is the master branch. :: 15 | 16 | # clone the repository 17 | $ git clone https://github.com/pallets/flask 18 | $ cd flask 19 | # checkout the correct version 20 | $ git tag # shows the tagged versions 21 | $ git checkout latest-tag-found-above 22 | $ cd examples/tutorial 23 | 24 | Create a virtualenv and activate it:: 25 | 26 | $ python3 -m venv venv 27 | $ . venv/bin/activate 28 | 29 | Or on Windows cmd:: 30 | 31 | $ py -3 -m venv venv 32 | $ venv\Scripts\activate.bat 33 | 34 | Install Flaskr:: 35 | 36 | $ pip install -e . 37 | 38 | Or if you are using the master branch, install Flask from source before 39 | installing Flaskr:: 40 | 41 | $ pip install -e ../.. 42 | $ pip install -e . 43 | 44 | 45 | Run 46 | --- 47 | 48 | :: 49 | 50 | $ export FLASK_APP=flaskr 51 | $ export FLASK_ENV=development 52 | $ flask init-db 53 | $ flask run 54 | 55 | Or on Windows cmd:: 56 | 57 | > set FLASK_APP=flaskr 58 | > set FLASK_ENV=development 59 | > flask init-db 60 | > flask run 61 | 62 | Open http://127.0.0.1:5000 in a browser. 63 | 64 | 65 | Test 66 | ---- 67 | 68 | :: 69 | 70 | $ pip install '.[test]' 71 | $ pytest 72 | 73 | Run with coverage report:: 74 | 75 | $ coverage run -m pytest 76 | $ coverage report 77 | $ coverage html # open htmlcov/index.html in a browser 78 | -------------------------------------------------------------------------------- /flask-basic/azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # To use this pipeline standalone, uncomment the `trigger` 2 | # and `name` stanzas. As-is, the pipeline is suitable for 3 | # importing as a template 4 | # 5 | # trigger: 6 | # - master 7 | # name: $(Date:yyyyMMdd)$(Rev:.r) 8 | jobs: 9 | 10 | - job: 'flask_basic' 11 | pool: 12 | vmImage: 'Ubuntu-16.04' 13 | strategy: 14 | matrix: 15 | Python36: 16 | python.version: '3.6' 17 | Python37: 18 | python.version: '3.7' 19 | maxParallel: 2 20 | 21 | steps: 22 | - task: UsePythonVersion@0 23 | inputs: 24 | versionSpec: '$(python.version)' 25 | architecture: 'x64' 26 | 27 | - script: | 28 | python -m pip install --upgrade pip 29 | cd flask-basic 30 | pip install '.[test]' 31 | displayName: 'Install dependencies' 32 | 33 | - script: | 34 | pip install pytest 35 | cd flask-basic 36 | pytest --junitxml=../reports/flask-basic.xml 37 | displayName: 'Run tests' 38 | 39 | - task: PublishTestResults@2 40 | inputs: 41 | testResultsFiles: 'reports/flask-basic.xml' 42 | testRunTitle: '$(Agent.OS) - $(Build.BuildNumber)[$(Agent.JobName)] - Python $(python.version)' 43 | condition: succeededOrFailed() 44 | 45 | - job: 'flask_basic_with_coverage' 46 | pool: 47 | vmImage: 'Ubuntu-16.04' 48 | strategy: 49 | matrix: 50 | Python36: 51 | python.version: '3.6' 52 | Python37: 53 | python.version: '3.7' 54 | maxParallel: 2 55 | 56 | steps: 57 | - task: UsePythonVersion@0 58 | inputs: 59 | versionSpec: '$(python.version)' 60 | architecture: 'x64' 61 | 62 | - script: | 63 | python -m pip install --upgrade pip 64 | cd flask-basic 65 | pip install '.[test]' 66 | displayName: 'Install dependencies' 67 | 68 | - script: | 69 | pip install pytest coverage 70 | cd flask-basic 71 | coverage run -m pytest --junitxml=../reports/flask-basic-coverage.xml 72 | coverage report 73 | displayName: 'Run tests and coverage' 74 | 75 | - task: PublishTestResults@2 76 | inputs: 77 | testResultsFiles: 'reports/flask-basic-coverage.xml' 78 | testRunTitle: '$(Agent.OS) - $(Build.BuildNumber)[$(Agent.JobName)] - Python $(python.version)' 79 | condition: succeededOrFailed() 80 | -------------------------------------------------------------------------------- /flask-basic/flaskr/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from flask import Flask 4 | 5 | 6 | def create_app(test_config=None): 7 | """Create and configure an instance of the Flask application.""" 8 | app = Flask(__name__, instance_relative_config=True) 9 | app.config.from_mapping( 10 | # a default secret that should be overridden by instance config 11 | SECRET_KEY='dev', 12 | # store the database in the instance folder 13 | DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), 14 | ) 15 | 16 | if test_config is None: 17 | # load the instance config, if it exists, when not testing 18 | app.config.from_pyfile('config.py', silent=True) 19 | else: 20 | # load the test config if passed in 21 | app.config.update(test_config) 22 | 23 | # ensure the instance folder exists 24 | try: 25 | os.makedirs(app.instance_path) 26 | except OSError: 27 | pass 28 | 29 | @app.route('/hello') 30 | def hello(): 31 | return 'Hello, World!' 32 | 33 | # register the database commands 34 | from flaskr import db 35 | db.init_app(app) 36 | 37 | # apply the blueprints to the app 38 | from flaskr import auth, blog 39 | app.register_blueprint(auth.bp) 40 | app.register_blueprint(blog.bp) 41 | 42 | # make url_for('index') == url_for('blog.index') 43 | # in another app, you might define a separate main index here with 44 | # app.route, while giving the blog blueprint a url_prefix, but for 45 | # the tutorial the blog will be the main index 46 | app.add_url_rule('/', endpoint='index') 47 | 48 | return app 49 | -------------------------------------------------------------------------------- /flask-basic/flaskr/auth.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | from flask import ( 4 | Blueprint, flash, g, redirect, render_template, request, session, url_for 5 | ) 6 | from werkzeug.security import check_password_hash, generate_password_hash 7 | 8 | from flaskr.db import get_db 9 | 10 | bp = Blueprint('auth', __name__, url_prefix='/auth') 11 | 12 | 13 | def login_required(view): 14 | """View decorator that redirects anonymous users to the login page.""" 15 | @functools.wraps(view) 16 | def wrapped_view(**kwargs): 17 | if g.user is None: 18 | return redirect(url_for('auth.login')) 19 | 20 | return view(**kwargs) 21 | 22 | return wrapped_view 23 | 24 | 25 | @bp.before_app_request 26 | def load_logged_in_user(): 27 | """If a user id is stored in the session, load the user object from 28 | the database into ``g.user``.""" 29 | user_id = session.get('user_id') 30 | 31 | if user_id is None: 32 | g.user = None 33 | else: 34 | g.user = get_db().execute( 35 | 'SELECT * FROM user WHERE id = ?', (user_id,) 36 | ).fetchone() 37 | 38 | 39 | @bp.route('/register', methods=('GET', 'POST')) 40 | def register(): 41 | """Register a new user. 42 | 43 | Validates that the username is not already taken. Hashes the 44 | password for security. 45 | """ 46 | if request.method == 'POST': 47 | username = request.form['username'] 48 | password = request.form['password'] 49 | db = get_db() 50 | error = None 51 | 52 | if not username: 53 | error = 'Username is required.' 54 | elif not password: 55 | error = 'Password is required.' 56 | elif db.execute( 57 | 'SELECT id FROM user WHERE username = ?', (username,) 58 | ).fetchone() is not None: 59 | error = 'User {0} is already registered.'.format(username) 60 | 61 | if error is None: 62 | # the name is available, store it in the database and go to 63 | # the login page 64 | db.execute( 65 | 'INSERT INTO user (username, password) VALUES (?, ?)', 66 | (username, generate_password_hash(password)) 67 | ) 68 | db.commit() 69 | return redirect(url_for('auth.login')) 70 | 71 | flash(error) 72 | 73 | return render_template('auth/register.html') 74 | 75 | 76 | @bp.route('/login', methods=('GET', 'POST')) 77 | def login(): 78 | """Log in a registered user by adding the user id to the session.""" 79 | if request.method == 'POST': 80 | username = request.form['username'] 81 | password = request.form['password'] 82 | db = get_db() 83 | error = None 84 | user = db.execute( 85 | 'SELECT * FROM user WHERE username = ?', (username,) 86 | ).fetchone() 87 | 88 | if user is None: 89 | error = 'Incorrect username.' 90 | elif not check_password_hash(user['password'], password): 91 | error = 'Incorrect password.' 92 | 93 | if error is None: 94 | # store the user id in a new session and return to the index 95 | session.clear() 96 | session['user_id'] = user['id'] 97 | return redirect(url_for('index')) 98 | 99 | flash(error) 100 | 101 | return render_template('auth/login.html') 102 | 103 | 104 | @bp.route('/logout') 105 | def logout(): 106 | """Clear the current session, including the stored user id.""" 107 | session.clear() 108 | return redirect(url_for('index')) 109 | -------------------------------------------------------------------------------- /flask-basic/flaskr/blog.py: -------------------------------------------------------------------------------- 1 | from flask import ( 2 | Blueprint, flash, g, redirect, render_template, request, url_for 3 | ) 4 | from werkzeug.exceptions import abort 5 | 6 | from flaskr.auth import login_required 7 | from flaskr.db import get_db 8 | 9 | bp = Blueprint('blog', __name__) 10 | 11 | 12 | @bp.route('/') 13 | def index(): 14 | """Show all the posts, most recent first.""" 15 | db = get_db() 16 | posts = db.execute( 17 | 'SELECT p.id, title, body, created, author_id, username' 18 | ' FROM post p JOIN user u ON p.author_id = u.id' 19 | ' ORDER BY created DESC' 20 | ).fetchall() 21 | return render_template('blog/index.html', posts=posts) 22 | 23 | 24 | def get_post(id, check_author=True): 25 | """Get a post and its author by id. 26 | 27 | Checks that the id exists and optionally that the current user is 28 | the author. 29 | 30 | :param id: id of post to get 31 | :param check_author: require the current user to be the author 32 | :return: the post with author information 33 | :raise 404: if a post with the given id doesn't exist 34 | :raise 403: if the current user isn't the author 35 | """ 36 | post = get_db().execute( 37 | 'SELECT p.id, title, body, created, author_id, username' 38 | ' FROM post p JOIN user u ON p.author_id = u.id' 39 | ' WHERE p.id = ?', 40 | (id,) 41 | ).fetchone() 42 | 43 | if post is None: 44 | abort(404, "Post id {0} doesn't exist.".format(id)) 45 | 46 | if check_author and post['author_id'] != g.user['id']: 47 | abort(403) 48 | 49 | return post 50 | 51 | 52 | @bp.route('/create', methods=('GET', 'POST')) 53 | @login_required 54 | def create(): 55 | """Create a new post for the current user.""" 56 | if request.method == 'POST': 57 | title = request.form['title'] 58 | body = request.form['body'] 59 | error = None 60 | 61 | if not title: 62 | error = 'Title is required.' 63 | 64 | if error is not None: 65 | flash(error) 66 | else: 67 | db = get_db() 68 | db.execute( 69 | 'INSERT INTO post (title, body, author_id)' 70 | ' VALUES (?, ?, ?)', 71 | (title, body, g.user['id']) 72 | ) 73 | db.commit() 74 | return redirect(url_for('blog.index')) 75 | 76 | return render_template('blog/create.html') 77 | 78 | 79 | @bp.route('/{{ post['body'] }}
23 |