├── test
├── cors
│ ├── __init__.py
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── etc-hosts.png
│ │ ├── test-google.png
│ │ └── test-google-https.png
│ ├── app.py
│ ├── static
│ │ └── js
│ │ │ ├── test_google.js
│ │ │ ├── test_get_by_token.js
│ │ │ ├── test_post_by_token.js
│ │ │ └── test_post_by_session.js
│ ├── app_ssl.py
│ ├── templates
│ │ └── index.html
│ └── README.md
└── rest_api
│ ├── requirements.txt
│ ├── screenshots
│ ├── pytest.png
│ ├── user_table_after.png
│ └── user_table_before.png
│ └── README.md
├── drf
├── drf_crud
│ ├── app
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── __init__.py
│ │ │ └── 0001_initial.py
│ │ ├── urls.py
│ │ ├── models.py
│ │ ├── serializers.py
│ │ └── views.py
│ ├── project
│ │ ├── __init__.py
│ │ ├── urls.py
│ │ ├── asgi.py
│ │ └── wsgi.py
│ ├── screenshots
│ │ ├── login.png
│ │ ├── get_root.png
│ │ ├── beverages_1.png
│ │ ├── categories.png
│ │ ├── post_coffee.png
│ │ ├── categories_1.png
│ │ └── post_americano.png
│ ├── requirements.txt
│ ├── manage.py
│ └── README.md
├── drf_minimal
│ ├── app
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ └── __init__.py
│ │ ├── serializers.py
│ │ └── views.py
│ ├── project
│ │ ├── __init__.py
│ │ ├── urls.py
│ │ ├── asgi.py
│ │ └── wsgi.py
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── get_root.png
│ │ ├── get_users.png
│ │ ├── get_users_1.png
│ │ ├── get_users_2.png
│ │ ├── post_result.png
│ │ ├── post_new_user.png
│ │ ├── api-auth_login.png
│ │ └── get_users_admin.png
│ ├── manage.py
│ └── README.md
├── drf_swagger
│ ├── app
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ └── __init__.py
│ │ ├── serializers.py
│ │ └── views.py
│ ├── project
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── wsgi.py
│ │ └── urls.py
│ ├── screenshots
│ │ ├── swagger1.png
│ │ ├── swagger2.png
│ │ └── swagger3.png
│ ├── requirements.txt
│ ├── manage.py
│ └── README.md
└── drf_testing
│ ├── app
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ │ └── 0001_initial.py
│ ├── urls.py
│ ├── models.py
│ ├── serializers.py
│ └── views.py
│ ├── project
│ ├── __init__.py
│ ├── urls.py
│ ├── asgi.py
│ └── wsgi.py
│ ├── requirements.txt
│ ├── screenshots
│ └── test_result.png
│ ├── README.md
│ └── manage.py
├── fastapi
├── fastapi_docker
│ ├── app
│ │ ├── __init__.py
│ │ └── main.py
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── localhost_8000.png
│ │ ├── app_fastapi_app.png
│ │ └── images_fastapi_docker.png
│ ├── Dockerfile
│ └── README.md
├── fastapi_static
│ ├── app
│ │ └── __init__.py
│ ├── root.css
│ ├── static
│ │ ├── style.css
│ │ └── index.html
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── root_css.png
│ │ ├── static_style_css.png
│ │ ├── static_index_html.png
│ │ └── static_index_html_source.png
│ ├── main.py
│ └── README.md
├── fastapi_api_router
│ ├── app
│ │ ├── __init__.py
│ │ └── api
│ │ │ ├── __init__.py
│ │ │ ├── endpoints
│ │ │ ├── __init__.py
│ │ │ ├── items.py
│ │ │ └── users.py
│ │ │ └── api.py
│ ├── requirements.txt
│ ├── main.py
│ ├── screenshots
│ │ ├── get_items.png
│ │ └── get_users.png
│ └── README.md
├── fastapi_request_files
│ ├── hello.txt
│ ├── world.txt
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── browser.png
│ │ ├── choose_files.png
│ │ ├── result_bytes.png
│ │ └── result_uploadfile.png
│ ├── README.md
│ └── main.py
├── fastapi_minimal
│ ├── .gitignore
│ ├── requirements.txt
│ ├── main.py
│ └── README.md
├── fastapi_cache_redis
│ ├── .gitignore
│ ├── requirements.txt
│ ├── screenshots
│ │ └── process_time.png
│ ├── main.py
│ └── README.md
├── fastapi_email_login_jwt_mysql
│ ├── app
│ │ ├── api
│ │ │ ├── __init__.py
│ │ │ ├── api_v1
│ │ │ │ ├── __init__.py
│ │ │ │ └── endpoints
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ ├── login.py
│ │ │ │ │ └── users.py
│ │ │ ├── api.py
│ │ │ └── depends.py
│ │ ├── core
│ │ │ ├── __init__.py
│ │ │ ├── config.py
│ │ │ └── security.py
│ │ ├── crud
│ │ │ ├── __init__.py
│ │ │ ├── user.py
│ │ │ └── base.py
│ │ ├── db
│ │ │ ├── __init__.py
│ │ │ ├── base_class.py
│ │ │ ├── session.py
│ │ │ └── init_db.py
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ └── user.py
│ │ └── schemas
│ │ │ ├── __init__.py
│ │ │ ├── token.py
│ │ │ └── user.py
│ ├── screenshots
│ │ ├── init_db.png
│ │ ├── openapi.png
│ │ ├── running.png
│ │ ├── register_user.png
│ │ ├── users_me_new_user.png
│ │ ├── patch_users_me_password.png
│ │ ├── patch_users_me_beaer_token.png
│ │ ├── login_access_token_new_user.png
│ │ ├── get_users_by_user_id_superuser.png
│ │ ├── patch_users_me_with_wrong_token.png
│ │ ├── get_users_by_user_id_normal_user.png
│ │ ├── login_access_token_first_superuser.png
│ │ ├── patch_users_by_user_id_normal_user.png
│ │ └── patch_users_by_user_id_superuser.png
│ ├── requirements.txt
│ └── main.py
├── fastapi_templates
│ ├── static
│ │ └── styles.css
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── get_items_3.png
│ │ ├── static_styles_css.png
│ │ └── items_static_styles_css.png
│ ├── templates
│ │ └── item.html
│ ├── main.py
│ └── README.md
├── fastapi_path_parameters
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── get_items.png
│ │ └── get_items_log.png
│ ├── main.py
│ └── README.md
├── fastapi_query_parameters
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── log.png
│ │ └── get_with_query_parameters.png
│ ├── main.py
│ └── README.md
├── fastapi_dependencies_first_steps
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── get_items.png
│ │ └── get_users.png
│ ├── common.py
│ ├── main.py
│ └── README.md
├── fastapi_request_body
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── post_items_log.png
│ │ └── post_items_with_json_body.png
│ ├── main.py
│ └── README.md
├── fastapi_form_data
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── html_login.png
│ │ ├── postman_log.png
│ │ ├── html_login_log.png
│ │ ├── html_login_result.png
│ │ └── postman_post_login.png
│ ├── main.py
│ ├── login.html
│ └── README.md
├── fastapi_oauth2
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── post_token.png
│ │ ├── get_users_me.png
│ │ └── get_users_me_with_wrong_token.png
│ ├── README.md
│ └── fastapi_oauth2.postman_collection.json
├── fastapi_orm_sqlite
│ ├── requirements.txt
│ ├── database.py
│ ├── schemas.py
│ ├── README.md
│ ├── models.py
│ ├── crud.py
│ └── main.py
├── fastapi_response_model
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── post_user.png
│ │ ├── get_items_baz.png
│ │ ├── get_items_foo.png
│ │ ├── get_items_bar_name.png
│ │ ├── get_items_bar_public.png
│ │ └── post_user_with_wrong_email.png
│ ├── README.md
│ └── main.py
├── fastapi_testing
│ ├── requirements.txt
│ ├── screenshos
│ │ ├── pytest.png
│ │ └── pytest_with_python.png
│ ├── main.py
│ ├── test_main.py
│ ├── README.md
│ ├── main_extended.py
│ └── test_main_extended.py
├── fastapi_orm_mysql
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── table_items.png
│ │ └── table_users.png
│ ├── database.py
│ ├── schemas.py
│ ├── README.md
│ ├── crud.py
│ ├── models.py
│ └── main.py
└── fastapi_oauth2_jwt
│ ├── screenshots
│ ├── post_token.png
│ ├── get_users_me.png
│ └── get_users_me_with_wrong_token.png
│ ├── requirements.txt
│ ├── README.md
│ └── fastapi_oauth2_jwt.postman_collection.json
├── django
├── django_minimal
│ ├── config
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── wsgi.py
│ │ └── urls.py
│ ├── requirements.txt
│ ├── screenshots
│ │ └── localhost8000.png
│ ├── manage.py
│ └── README.md
├── django_celery_worker
│ ├── mysite
│ │ ├── __init__.py
│ │ ├── celery.py
│ │ ├── asgi.py
│ │ ├── wsgi.py
│ │ └── urls.py
│ ├── task
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ └── __init__.py
│ │ ├── models.py
│ │ ├── tests.py
│ │ ├── admin.py
│ │ ├── tasks.py
│ │ ├── apps.py
│ │ └── views.py
│ ├── requirements.txt
│ ├── db.sqlite3
│ ├── images
│ │ ├── GET.png
│ │ └── POST.png
│ ├── manage.py
│ └── README.md
├── django_admin_register_app
│ ├── cafe
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── __init__.py
│ │ │ └── 0001_initial.py
│ │ ├── admin.py
│ │ ├── apps.py
│ │ └── models.py
│ ├── config
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── wsgi.py
│ │ └── urls.py
│ ├── requirements.txt
│ ├── screenshots
│ │ ├── admin_login.png
│ │ ├── admin_page.png
│ │ ├── add_category.png
│ │ ├── register_model.png
│ │ ├── add_category_tea.png
│ │ ├── add_beverage_americano.png
│ │ ├── add_beverage_cafe_latte.png
│ │ ├── add_beverage_green_tea.png
│ │ └── admin_page_with_app_models.png
│ ├── manage.py
│ └── README.md
└── django_pytest_with_bakery
│ ├── mysite
│ ├── __init__.py
│ ├── asgi.py
│ ├── wsgi.py
│ └── urls.py
│ ├── shop
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ │ └── 0001_initial.py
│ ├── tests.py
│ ├── admin.py
│ ├── views.py
│ ├── apps.py
│ ├── models.py
│ └── test_models.py
│ ├── requirements.txt
│ ├── db.sqlite3
│ ├── pytest.ini
│ ├── manage.py
│ └── README.md
├── flask
├── flask_minimal
│ ├── requirements.txt
│ ├── app.py
│ ├── images
│ │ └── flask_is_running.png
│ ├── Dockerfile
│ └── README.md
├── flask_ajax
│ ├── requirements.txt
│ ├── static
│ │ ├── css
│ │ │ └── common.css
│ │ └── images
│ │ │ ├── 01.jpg
│ │ │ ├── 02.png
│ │ │ ├── 01_result.jpg
│ │ │ └── 02_result.jpg
│ ├── images
│ │ ├── 01.png
│ │ └── 02.png
│ ├── templates
│ │ ├── ajax_image.html
│ │ └── index.html
│ ├── app.py
│ └── README.md
├── flask_orm
│ ├── requirements.txt
│ ├── db.sqlite
│ ├── images
│ │ ├── home.png
│ │ ├── get_munus.png
│ │ ├── post_menus.png
│ │ ├── put_menus.png
│ │ ├── get_menu_id_3.png
│ │ ├── delete_menu_id_5.png
│ │ ├── get_menu_id_6_after_put.png
│ │ ├── get_menus_after_delete.png
│ │ └── get_menu_id_6_after_post.png
│ ├── list.py
│ ├── init_db.py
│ ├── README.md
│ └── app.py
└── flask_file_upload
│ ├── static
│ └── files
│ │ └── README.md
│ ├── templates
│ ├── uploaded_image.html
│ ├── index.html
│ ├── upload.html
│ ├── upload_test_with_secure_filename.html
│ └── upload_simple_button.html
│ └── app.py
├── event_streaming
└── kafka_python
│ ├── requirements.txt
│ ├── sceenshots
│ └── consumer.png
│ ├── consumer.py
│ ├── producer.py
│ └── README.md
├── protocol
└── grpc_simple_message
│ ├── requirements.txt
│ ├── protos
│ └── user.proto
│ ├── user_client.py
│ ├── user_server.py
│ ├── README.md
│ └── user_pb2.py
├── docker
└── docker_cron
│ ├── crontab-example
│ ├── README.md
│ ├── main.py
│ └── Dockerfile
└── LICENSE
/test/cors/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_crud/project/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_minimal/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_swagger/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_minimal/project/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_swagger/project/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_testing/project/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_minimal/config/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_minimal/app/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_swagger/app/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/cors/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==2.2.2
2 |
--------------------------------------------------------------------------------
/django/django_celery_worker/mysite/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/api/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/hello.txt:
--------------------------------------------------------------------------------
1 | hello
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/world.txt:
--------------------------------------------------------------------------------
1 | world
--------------------------------------------------------------------------------
/flask/flask_minimal/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==2.0.1
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/config/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/mysite/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_minimal/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | venv
3 |
--------------------------------------------------------------------------------
/flask/flask_ajax/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==2.0.1
2 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/api/endpoints/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_cache_redis/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | venv
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/core/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/crud/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/db/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/models/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/schemas/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/api_v1/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/event_streaming/kafka_python/requirements.txt:
--------------------------------------------------------------------------------
1 | kafka-python==2.0.2
2 |
--------------------------------------------------------------------------------
/flask/flask_orm/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==2.0.0
2 | Flask-SQLAlchemy==2.5.1
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/api_v1/endpoints/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/root.css:
--------------------------------------------------------------------------------
1 | div {
2 | background-color: red;
3 | }
4 |
--------------------------------------------------------------------------------
/drf/drf_testing/requirements.txt:
--------------------------------------------------------------------------------
1 | Django==3.2.19
2 | djangorestframework==3.14.0
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/static/styles.css:
--------------------------------------------------------------------------------
1 | h1 {
2 | color: green;
3 | }
4 |
--------------------------------------------------------------------------------
/flask/flask_ajax/static/css/common.css:
--------------------------------------------------------------------------------
1 | body {
2 | background-color: black;
3 | }
--------------------------------------------------------------------------------
/flask/flask_file_upload/static/files/README.md:
--------------------------------------------------------------------------------
1 | Uploaded files will be saved here.
--------------------------------------------------------------------------------
/django/django_celery_worker/requirements.txt:
--------------------------------------------------------------------------------
1 | django==3.2.8
2 | celery==5.1.2
3 | redis==3.5.3
--------------------------------------------------------------------------------
/fastapi/fastapi_static/static/style.css:
--------------------------------------------------------------------------------
1 | div {
2 | background-color: lightgrey;
3 | }
4 |
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/requirements.txt:
--------------------------------------------------------------------------------
1 | grpcio==1.44.0
2 | grpcio-tools==1.44.0
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_minimal/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/test/rest_api/requirements.txt:
--------------------------------------------------------------------------------
1 | requests==2.28.1
2 | python-dotenv==0.21.0
3 | pytest==7.2.0
4 |
--------------------------------------------------------------------------------
/docker/docker_cron/crontab-example:
--------------------------------------------------------------------------------
1 | * * * * * python /home/app/main.py >> /home/app/main.log 2>&1
2 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | uvicorn[standard]
3 | jinja2==3.0.3
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.75.0
2 | uvicorn[standard]
3 | jinja2==3.0.3
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_path_parameters/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/fastapi/fastapi_query_parameters/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/templates/uploaded_image.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_cache_redis/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | uvicorn[standard]==0.17.6
3 | redis==4.2.2
4 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 |
--------------------------------------------------------------------------------
/django/django_minimal/requirements.txt:
--------------------------------------------------------------------------------
1 | # Django LTS 3.2.12 https://www.djangoproject.com/download/
2 | Django==3.2.12
3 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 |
3 | # Create your views here.
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_body/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install "uvicorn[standard]"
2 | fastapi==0.74.1
3 | pydantic==1.9.0
4 |
--------------------------------------------------------------------------------
/flask/flask_orm/db.sqlite:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/db.sqlite
--------------------------------------------------------------------------------
/docker/docker_cron/README.md:
--------------------------------------------------------------------------------
1 | # Docker Cron Example
2 |
3 | ## Run
4 | ```shell
5 | docker build -t cron-example .
6 | ```
7 |
--------------------------------------------------------------------------------
/docker/docker_cron/main.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 |
3 | if __name__ == '__main__':
4 | print(datetime.now())
5 |
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 | python-multipart==0.0.5
4 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/requirements.txt:
--------------------------------------------------------------------------------
1 | # Django LTS 3.2.12 https://www.djangoproject.com/download/
2 | Django==3.2.12
3 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/requirements.txt:
--------------------------------------------------------------------------------
1 | django==3.2.8
2 | model_bakery==1.4.0
3 | pytest==6.2.3
4 | pytest-django==4.2.0
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 | python-multipart==0.0.5
4 |
--------------------------------------------------------------------------------
/flask/flask_ajax/images/01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/images/01.png
--------------------------------------------------------------------------------
/flask/flask_ajax/images/02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/images/02.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/home.png
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/login.png
--------------------------------------------------------------------------------
/test/cors/screenshots/etc-hosts.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/cors/screenshots/etc-hosts.png
--------------------------------------------------------------------------------
/django/django_celery_worker/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_celery_worker/db.sqlite3
--------------------------------------------------------------------------------
/drf/drf_crud/requirements.txt:
--------------------------------------------------------------------------------
1 | # Django LTS 3.2.12 https://www.djangoproject.com/download/
2 | Django==3.2.12
3 | djangorestframework==3.12.4
4 |
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/get_root.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/get_root.png
--------------------------------------------------------------------------------
/drf/drf_minimal/requirements.txt:
--------------------------------------------------------------------------------
1 | # Django LTS 3.2.12 https://www.djangoproject.com/download/
2 | Django==3.2.12
3 | djangorestframework==3.12.4
4 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 | pydantic==1.9.0
4 | python-multipart==0.0.5
5 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install "uvicorn[standard]"
3 | sqlalchemy==1.4.31
4 | pydantic==1.9.0
5 |
--------------------------------------------------------------------------------
/flask/flask_ajax/static/images/01.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/static/images/01.jpg
--------------------------------------------------------------------------------
/flask/flask_ajax/static/images/02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/static/images/02.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/get_munus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/get_munus.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/post_menus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/post_menus.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/put_menus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/put_menus.png
--------------------------------------------------------------------------------
/test/cors/screenshots/test-google.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/cors/screenshots/test-google.png
--------------------------------------------------------------------------------
/test/rest_api/screenshots/pytest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/rest_api/screenshots/pytest.png
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/beverages_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/beverages_1.png
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/categories.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/categories.png
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/post_coffee.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/post_coffee.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/get_root.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/get_root.png
--------------------------------------------------------------------------------
/drf/drf_swagger/screenshots/swagger1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_swagger/screenshots/swagger1.png
--------------------------------------------------------------------------------
/drf/drf_swagger/screenshots/swagger2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_swagger/screenshots/swagger2.png
--------------------------------------------------------------------------------
/drf/drf_swagger/screenshots/swagger3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_swagger/screenshots/swagger3.png
--------------------------------------------------------------------------------
/flask/flask_ajax/templates/ajax_image.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/flask/flask_orm/images/get_menu_id_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/get_menu_id_3.png
--------------------------------------------------------------------------------
/django/django_celery_worker/images/GET.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_celery_worker/images/GET.png
--------------------------------------------------------------------------------
/django/django_celery_worker/images/POST.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_celery_worker/images/POST.png
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_pytest_with_bakery/db.sqlite3
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/categories_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/categories_1.png
--------------------------------------------------------------------------------
/drf/drf_crud/screenshots/post_americano.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_crud/screenshots/post_americano.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/get_users.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/get_users.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/get_users_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/get_users_1.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/get_users_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/get_users_2.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/post_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/post_result.png
--------------------------------------------------------------------------------
/drf/drf_testing/screenshots/test_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_testing/screenshots/test_result.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/delete_menu_id_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/delete_menu_id_5.png
--------------------------------------------------------------------------------
/test/cors/screenshots/test-google-https.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/cors/screenshots/test-google-https.png
--------------------------------------------------------------------------------
/django/django_celery_worker/task/tasks.py:
--------------------------------------------------------------------------------
1 | from mysite.celery import app
2 |
3 |
4 | @app.task
5 | def add(number1, number2):
6 | return number1 + number2
7 |
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/post_new_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/post_new_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install "uvicorn[standard]"
2 | fastapi==0.74.1
3 | pydantic==1.9.0
4 | # pip install "pydantic[email]"
5 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install "uvicorn[standard]"
2 | fastapi==0.74.1
3 | pytest==7.0.1
4 |
5 | # For pytest
6 | requests==2.27.1
7 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/screenshos/pytest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_testing/screenshos/pytest.png
--------------------------------------------------------------------------------
/flask/flask_ajax/static/images/01_result.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/static/images/01_result.jpg
--------------------------------------------------------------------------------
/flask/flask_ajax/static/images/02_result.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_ajax/static/images/02_result.jpg
--------------------------------------------------------------------------------
/flask/flask_minimal/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 |
3 | app = Flask(__name__)
4 |
5 |
6 | @app.route('/')
7 | def hello():
8 | return 'Hello World!'
9 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | DJANGO_SETTINGS_MODULE = mysite.settings
3 | python_files = tests.py test_*.py *_tests.py
4 | addopts = -s
5 |
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/api-auth_login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/api-auth_login.png
--------------------------------------------------------------------------------
/drf/drf_minimal/screenshots/get_users_admin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/drf/drf_minimal/screenshots/get_users_admin.png
--------------------------------------------------------------------------------
/drf/drf_swagger/requirements.txt:
--------------------------------------------------------------------------------
1 | # Django LTS 3.2.12 https://www.djangoproject.com/download/
2 | Django==3.2.12
3 | djangorestframework==3.12.4
4 | drf-yasg==1.20.0
5 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install "uvicorn[standard]"
2 | fastapi==0.74.1
3 | sqlalchemy==1.4.31
4 | pydantic==1.9.0
5 | mysqlclient==2.1.0
6 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/screenshots/root_css.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_static/screenshots/root_css.png
--------------------------------------------------------------------------------
/flask/flask_minimal/images/flask_is_running.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_minimal/images/flask_is_running.png
--------------------------------------------------------------------------------
/test/rest_api/screenshots/user_table_after.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/rest_api/screenshots/user_table_after.png
--------------------------------------------------------------------------------
/test/rest_api/screenshots/user_table_before.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/test/rest_api/screenshots/user_table_before.png
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 | from app.api.api import api_router
3 |
4 | app = FastAPI()
5 |
6 | app.include_router(api_router)
7 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/screenshots/post_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2/screenshots/post_token.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/get_menu_id_6_after_put.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/get_menu_id_6_after_put.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/get_menus_after_delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/get_menus_after_delete.png
--------------------------------------------------------------------------------
/django/django_minimal/screenshots/localhost8000.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_minimal/screenshots/localhost8000.png
--------------------------------------------------------------------------------
/event_streaming/kafka_python/sceenshots/consumer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/event_streaming/kafka_python/sceenshots/consumer.png
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/screenshots/get_items.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_api_router/screenshots/get_items.png
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/screenshots/get_users.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_api_router/screenshots/get_users.png
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/screenshots/localhost_8000.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_docker/screenshots/localhost_8000.png
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/screenshots/html_login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_form_data/screenshots/html_login.png
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/screenshots/postman_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_form_data/screenshots/postman_log.png
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/screenshots/get_users_me.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2/screenshots/get_users_me.png
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/screenshots/post_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2_jwt/screenshots/post_token.png
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/screenshots/table_items.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_orm_mysql/screenshots/table_items.png
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/screenshots/table_users.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_orm_mysql/screenshots/table_users.png
--------------------------------------------------------------------------------
/fastapi/fastapi_query_parameters/screenshots/log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_query_parameters/screenshots/log.png
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/screenshots/browser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_files/screenshots/browser.png
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/screenshots/get_items_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_templates/screenshots/get_items_3.png
--------------------------------------------------------------------------------
/flask/flask_orm/images/get_menu_id_6_after_post.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/flask/flask_orm/images/get_menu_id_6_after_post.png
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/screenshots/app_fastapi_app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_docker/screenshots/app_fastapi_app.png
--------------------------------------------------------------------------------
/fastapi/fastapi_minimal/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 |
3 | app = FastAPI()
4 |
5 |
6 | @app.get("/")
7 | async def root():
8 | return {"message": "Hello World"}
9 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/screenshots/get_users_me.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2_jwt/screenshots/get_users_me.png
--------------------------------------------------------------------------------
/fastapi/fastapi_static/screenshots/static_style_css.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_static/screenshots/static_style_css.png
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 |
3 | app = FastAPI()
4 |
5 |
6 | @app.get("/")
7 | async def read_main():
8 | return {"msg": "Hello World"}
9 |
--------------------------------------------------------------------------------
/fastapi/fastapi_cache_redis/screenshots/process_time.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_cache_redis/screenshots/process_time.png
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/screenshots/html_login_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_form_data/screenshots/html_login_log.png
--------------------------------------------------------------------------------
/fastapi/fastapi_path_parameters/screenshots/get_items.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_path_parameters/screenshots/get_items.png
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/screenshots/choose_files.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_files/screenshots/choose_files.png
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/screenshots/result_bytes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_files/screenshots/result_bytes.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/post_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/post_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_static/screenshots/static_index_html.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_static/screenshots/static_index_html.png
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/screenshos/pytest_with_python.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_testing/screenshos/pytest_with_python.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/admin_login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/admin_login.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/admin_page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/admin_page.png
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/screenshots/images_fastapi_docker.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_docker/screenshots/images_fastapi_docker.png
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/screenshots/html_login_result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_form_data/screenshots/html_login_result.png
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/screenshots/postman_post_login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_form_data/screenshots/postman_post_login.png
--------------------------------------------------------------------------------
/fastapi/fastapi_request_body/screenshots/post_items_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_body/screenshots/post_items_log.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/get_items_baz.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/get_items_baz.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/get_items_foo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/get_items_foo.png
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/screenshots/static_styles_css.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_templates/screenshots/static_styles_css.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/add_category.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/add_category.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/register_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/register_model.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/init_db.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/init_db.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/openapi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/openapi.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/running.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/running.png
--------------------------------------------------------------------------------
/fastapi/fastapi_path_parameters/screenshots/get_items_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_path_parameters/screenshots/get_items_log.png
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/screenshots/result_uploadfile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_files/screenshots/result_uploadfile.png
--------------------------------------------------------------------------------
/fastapi/fastapi_static/screenshots/static_index_html_source.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_static/screenshots/static_index_html_source.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/add_category_tea.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/add_category_tea.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/get_items_bar_name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/get_items_bar_name.png
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/screenshots/items_static_styles_css.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_templates/screenshots/items_static_styles_css.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | from .models import Category, Beverage
4 |
5 | admin.site.register(Category)
6 | admin.site.register(Beverage)
7 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class TaskConfig(AppConfig):
5 | default_auto_field = 'django.db.models.BigAutoField'
6 | name = 'task'
7 |
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/screenshots/get_items.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_dependencies_first_steps/screenshots/get_items.png
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/screenshots/get_users.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_dependencies_first_steps/screenshots/get_users.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/register_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/register_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/screenshots/get_users_me_with_wrong_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2/screenshots/get_users_me_with_wrong_token.png
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install "uvicorn[standard]"
2 | # pip install "passlib[bcrypt]"
3 | fastapi==0.74.1
4 | pydantic==1.9.0
5 | python-multipart==0.0.5
6 | python-jose==3.3.0
7 |
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/get_items_bar_public.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/get_items_bar_public.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class CafeConfig(AppConfig):
5 | default_auto_field = 'django.db.models.BigAutoField'
6 | name = 'cafe'
7 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class BakeryConfig(AppConfig):
5 | default_auto_field = 'django.db.models.BigAutoField'
6 | name = 'shop'
7 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_body/screenshots/post_items_with_json_body.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_request_body/screenshots/post_items_with_json_body.png
--------------------------------------------------------------------------------
/fastapi/fastapi_static/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 | from fastapi.staticfiles import StaticFiles
3 |
4 | app = FastAPI()
5 |
6 | app.mount("/static", StaticFiles(directory="static"), name="static")
7 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/add_beverage_americano.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/add_beverage_americano.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/add_beverage_cafe_latte.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/add_beverage_cafe_latte.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/add_beverage_green_tea.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/add_beverage_green_tea.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/users_me_new_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/users_me_new_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/screenshots/get_users_me_with_wrong_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_oauth2_jwt/screenshots/get_users_me_with_wrong_token.png
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/screenshots/post_user_with_wrong_email.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_response_model/screenshots/post_user_with_wrong_email.png
--------------------------------------------------------------------------------
/django/django_admin_register_app/screenshots/admin_page_with_app_models.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/django/django_admin_register_app/screenshots/admin_page_with_app_models.png
--------------------------------------------------------------------------------
/fastapi/fastapi_query_parameters/screenshots/get_with_query_parameters.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_query_parameters/screenshots/get_with_query_parameters.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_password.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_password.png
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/common.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 |
4 | async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
5 | return {"q": q, "skip": skip, "limit": limit}
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_beaer_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_beaer_token.png
--------------------------------------------------------------------------------
/event_streaming/kafka_python/consumer.py:
--------------------------------------------------------------------------------
1 | import kafka
2 |
3 |
4 | consumer = kafka.KafkaConsumer(bootstrap_servers='localhost:9092')
5 | consumer.subscribe(topics=['quickstart-events'])
6 | for msg in consumer:
7 | print(msg)
8 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/login_access_token_new_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/login_access_token_new_user.png
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 |
4 | class Customer(models.Model):
5 | name = models.CharField(max_length=30)
6 | email = models.EmailField()
7 | age = models.IntegerField()
8 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/get_users_by_user_id_superuser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/get_users_by_user_id_superuser.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_with_wrong_token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_me_with_wrong_token.png
--------------------------------------------------------------------------------
/fastapi/fastapi_path_parameters/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 |
3 | app = FastAPI()
4 |
5 |
6 | @app.get("/items/{item_id}")
7 | async def read_item(item_id):
8 | print(item_id)
9 | return {"item_id": item_id}
10 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/get_users_by_user_id_normal_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/get_users_by_user_id_normal_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/login_access_token_first_superuser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/login_access_token_first_superuser.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_by_user_id_normal_user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_by_user_id_normal_user.png
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_by_user_id_superuser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/taptorestart/python-backend-examples/HEAD/fastapi/fastapi_email_login_jwt_mysql/screenshots/patch_users_by_user_id_superuser.png
--------------------------------------------------------------------------------
/event_streaming/kafka_python/producer.py:
--------------------------------------------------------------------------------
1 | import kafka
2 |
3 |
4 | producer = kafka.KafkaProducer(bootstrap_servers='localhost:9092')
5 | future = producer.send(topic='quickstart-events', key=b'foo', value=b'bar')
6 | result = future.get(timeout=60)
7 |
--------------------------------------------------------------------------------
/flask/flask_minimal/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.8-slim-buster
2 |
3 | WORKDIR /app
4 |
5 | COPY requirements.txt requirements.txt
6 |
7 | RUN pip3 install -r requirements.txt
8 |
9 | COPY . .
10 |
11 | CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
--------------------------------------------------------------------------------
/flask/flask_orm/list.py:
--------------------------------------------------------------------------------
1 | from app import Menu
2 |
3 |
4 | if __name__ == '__main__':
5 | for menu in Menu.query.all():
6 | print('id: {}'.format(menu.id))
7 | print('name: {}'.format(menu.name))
8 | print('price: {} WON'.format(menu.price))
9 |
--------------------------------------------------------------------------------
/django/django_celery_worker/mysite/celery.py:
--------------------------------------------------------------------------------
1 | import os
2 | from celery import Celery
3 |
4 |
5 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
6 | app = Celery("mysite")
7 | app.config_from_object("django.conf:settings", namespace="CELERY")
8 | app.autodiscover_tasks()
9 |
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI, Form
2 |
3 | app = FastAPI()
4 |
5 |
6 | @app.post("/login/")
7 | async def login(username: str = Form(...), password: str = Form(...)):
8 | print(username)
9 | print(password)
10 | return {"username": username}
11 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/schemas/token.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 | from pydantic import BaseModel
3 |
4 |
5 | class Token(BaseModel):
6 | access_token: str
7 | token_type: str
8 |
9 |
10 | class TokenPayload(BaseModel):
11 | sub: Optional[str] = None
12 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi==0.74.1
2 | # pip install uvicorn[standard]
3 | python-dotenv==0.19.2
4 | sqlalchemy==1.4.31
5 | pydantic==1.9.0
6 | # pip install "pydantic[email]"
7 | mysqlclient==2.1.0
8 | python-jose==3.3.0
9 | # pip install "passlib[bcrypt]"
10 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/api/api.py:
--------------------------------------------------------------------------------
1 | from fastapi import APIRouter
2 |
3 | from app.api.endpoints import items, users
4 |
5 | api_router = APIRouter()
6 | api_router.include_router(users.router, prefix="/users", tags=["users"])
7 | api_router.include_router(items.router, prefix="/items", tags=["items"])
8 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/api.py:
--------------------------------------------------------------------------------
1 | from fastapi import APIRouter
2 |
3 | from app.api.api_v1.endpoints import login, users
4 |
5 | api_router = APIRouter()
6 | api_router.include_router(login.router, tags=["login"])
7 | api_router.include_router(users.router, prefix="/users", tags=["users"])
8 |
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.9
2 |
3 | WORKDIR /code
4 |
5 | COPY ./requirements.txt /code/requirements.txt
6 | RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
7 |
8 | COPY ./app /code/app
9 |
10 | CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
11 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/test_main.py:
--------------------------------------------------------------------------------
1 | from fastapi.testclient import TestClient
2 | from main import app
3 |
4 | client = TestClient(app)
5 |
6 |
7 | def test_read_main():
8 | response = client.get("/")
9 | assert response.status_code == 200
10 | assert response.json() == {"msg": "Hello World"}
11 |
--------------------------------------------------------------------------------
/docker/docker_cron/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.8-buster
2 |
3 | WORKDIR /home/app
4 |
5 | RUN apt-get update
6 | RUN apt-get install -y cron
7 | COPY . /home/app
8 | COPY crontab-example /etc/cron.d/crontab-example
9 |
10 | RUN chmod 0644 /etc/cron.d/crontab-example
11 | RUN crontab /etc/cron.d/crontab-example
12 | CMD ["cron", "-f"]
13 |
--------------------------------------------------------------------------------
/test/cors/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template
2 |
3 | app = Flask(__name__)
4 |
5 |
6 | @app.route('/')
7 | def index():
8 | return render_template('index.html')
9 |
10 |
11 | HOST = 'local.taptorestart.com'
12 | PORT = 8000
13 |
14 |
15 | if __name__ == '__main__':
16 | app.run(host=HOST, port=PORT, debug=True)
17 |
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/app/main.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 | from fastapi import FastAPI
3 |
4 | app = FastAPI()
5 |
6 |
7 | @app.get("/")
8 | def read_root():
9 | return {"Hello": "World"}
10 |
11 |
12 | @app.get("/items/{item_id}")
13 | def read_item(item_id: int, q: Optional[str] = None):
14 | return {"item_id": item_id, "q": q}
15 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/static/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | FastAPI Static Files
6 |
7 |
8 |
9 |
10 | Index
11 |
12 |
13 |
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/templates/item.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Item Details
4 |
5 |
6 |
7 |
8 |
9 | Item ID: {{ id }}
10 |
11 |
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/protos/user.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | package grpc;
4 |
5 | service UserService {
6 | rpc GetUser (UserRequest) returns (User) {}
7 | }
8 |
9 | message User {
10 | int32 id = 1;
11 | string email = 2;
12 | int32 is_active = 3;
13 | int32 is_superuser = 4;
14 | }
15 |
16 | message UserRequest {
17 | string email = 1;
18 | }
19 |
--------------------------------------------------------------------------------
/fastapi/fastapi_query_parameters/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 |
3 | app = FastAPI()
4 |
5 | fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
6 |
7 |
8 | @app.get("/items/")
9 | async def read_item(skip: int = 0, limit: int = 10):
10 | print(f'skip: {skip}')
11 | print(f'limit: {limit}')
12 | return fake_items_db[skip: skip + limit]
13 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/db/base_class.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 |
3 | from sqlalchemy.ext.declarative import as_declarative, declared_attr
4 |
5 |
6 | @as_declarative()
7 | class Base:
8 | id: Any
9 | __name__: str
10 | # Generate __tablename__ automatically
11 | @declared_attr
12 | def __tablename__(cls) -> str:
13 | return cls.__name__.lower()
14 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/api/endpoints/items.py:
--------------------------------------------------------------------------------
1 | from fastapi import APIRouter
2 |
3 | router = APIRouter()
4 |
5 | fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
6 |
7 |
8 | @router.get("/")
9 | async def read_item(skip: int = 0, limit: int = 10):
10 | print(f'skip: {skip}')
11 | print(f'limit: {limit}')
12 | return fake_items_db[skip: skip + limit]
13 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/app/api/endpoints/users.py:
--------------------------------------------------------------------------------
1 | from fastapi import APIRouter
2 |
3 | router = APIRouter()
4 |
5 | fake_name_db = [{"user_name": "John"}, {"user_name": "Ted"}, {"user_name": "James"}]
6 |
7 |
8 | @router.get("/")
9 | async def read_user(skip: int = 0, limit: int = 10):
10 | print(f'skip: {skip}')
11 | print(f'limit: {limit}')
12 | return fake_name_db[skip: skip + limit]
13 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import include
2 | from django.urls import path
3 | from rest_framework.routers import SimpleRouter
4 | from app.views import CategoryViewSet, BeverageViewSet
5 |
6 |
7 | router = SimpleRouter()
8 | router.register(r'categories', CategoryViewSet)
9 | router.register(r'beverages', BeverageViewSet)
10 |
11 | urlpatterns = [
12 | path('', include(router.urls)),
13 | ]
14 |
--------------------------------------------------------------------------------
/drf/drf_minimal/project/urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import include, path
2 | from rest_framework import routers
3 | from app import views
4 |
5 | router = routers.DefaultRouter()
6 | router.register(r'users', views.UserViewSet)
7 | router.register(r'groups', views.GroupViewSet)
8 |
9 | urlpatterns = [
10 | path('', include(router.urls)),
11 | path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
12 | ]
13 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_body/main.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | from fastapi import FastAPI
4 | from pydantic import BaseModel
5 |
6 |
7 | class Item(BaseModel):
8 | name: str
9 | description: Optional[str] = None
10 | price: float
11 | tax: Optional[float] = None
12 |
13 |
14 | app = FastAPI()
15 |
16 |
17 | @app.post("/items/")
18 | async def create_item(item: Item):
19 | print(item)
20 | return item
21 |
--------------------------------------------------------------------------------
/flask/flask_orm/init_db.py:
--------------------------------------------------------------------------------
1 | from app import db, Menu
2 |
3 |
4 | if __name__ == '__main__':
5 | db.create_all()
6 | db.session.add(Menu(name='Bulgogi', price=15000))
7 | db.session.add(Menu(name='Samgyeopsal', price=12000))
8 | db.session.add(Menu(name='Ddukbokki', price=4000))
9 | db.session.add(Menu(name='Bibimbap', price=8000))
10 | db.session.add(Menu(name='Seolleongtang', price=10000))
11 | db.session.commit()
12 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import include
2 | from django.urls import path
3 | from rest_framework.routers import SimpleRouter
4 |
5 | from app.views import CategoryViewSet, BeverageViewSet
6 |
7 | router = SimpleRouter()
8 | router.register(r'categories', CategoryViewSet, basename='category')
9 | router.register(r'beverages', BeverageViewSet, basename='beverage')
10 |
11 | urlpatterns = [
12 | path('', include(router.urls)),
13 | ]
14 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 |
3 | from app.api.api import api_router
4 | from app.core.config import settings
5 | from app.db.session import SessionLocal
6 | from app.db.init_db import init_db
7 |
8 |
9 | # Create first super user
10 | def init() -> None:
11 | db = SessionLocal()
12 | init_db(db)
13 |
14 |
15 | app = FastAPI()
16 | app.include_router(api_router, prefix=settings.API_V1_STR)
17 | init()
18 |
--------------------------------------------------------------------------------
/drf/drf_crud/project/urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import include, path
2 | from rest_framework import routers
3 | from app import views
4 |
5 | router = routers.DefaultRouter()
6 | router.register(r'users', views.UserViewSet)
7 | router.register(r'groups', views.GroupViewSet)
8 |
9 | urlpatterns = [
10 | path('', include(router.urls)),
11 | path('', include('app.urls')),
12 | path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
13 | ]
14 |
--------------------------------------------------------------------------------
/drf/drf_minimal/app/serializers.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import serializers
3 |
4 |
5 | class UserSerializer(serializers.HyperlinkedModelSerializer):
6 | class Meta:
7 | model = User
8 | fields = ['url', 'username', 'email', 'groups']
9 |
10 |
11 | class GroupSerializer(serializers.HyperlinkedModelSerializer):
12 | class Meta:
13 | model = Group
14 | fields = ['url', 'name']
15 |
--------------------------------------------------------------------------------
/drf/drf_swagger/app/serializers.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import serializers
3 |
4 |
5 | class UserSerializer(serializers.HyperlinkedModelSerializer):
6 | class Meta:
7 | model = User
8 | fields = ['url', 'username', 'email', 'groups']
9 |
10 |
11 | class GroupSerializer(serializers.HyperlinkedModelSerializer):
12 | class Meta:
13 | model = Group
14 | fields = ['url', 'name']
15 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/database.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import create_engine
2 | from sqlalchemy.ext.declarative import declarative_base
3 | from sqlalchemy.orm import sessionmaker
4 |
5 | SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
6 |
7 | engine = create_engine(
8 | SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
9 | )
10 | SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11 |
12 | Base = declarative_base()
13 |
--------------------------------------------------------------------------------
/drf/drf_testing/project/urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import include, path
2 | from rest_framework import routers
3 | from app import views
4 |
5 | router = routers.DefaultRouter()
6 | router.register(r'users', views.UserViewSet)
7 | router.register(r'groups', views.GroupViewSet)
8 |
9 | urlpatterns = [
10 | path('', include(router.urls)),
11 | path('', include('app.urls')),
12 | path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
13 | ]
14 |
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import Depends, FastAPI
2 | from common import common_parameters
3 |
4 | app = FastAPI()
5 |
6 |
7 | @app.get("/items/")
8 | async def read_items(page: int = 0, commons: dict = Depends(common_parameters)):
9 | print(page)
10 | commons[page] = page
11 | return commons
12 |
13 |
14 | @app.get("/users/")
15 | async def read_users(commons: dict = Depends(common_parameters)):
16 | return commons
17 |
--------------------------------------------------------------------------------
/drf/drf_crud/project/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for project project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_crud/project/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for project 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/3.2/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', 'project.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_minimal/project/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for project project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_minimal/project/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for project 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/3.2/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', 'project.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_swagger/project/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for project project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_swagger/project/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for project 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/3.2/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', 'project.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_testing/project/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for project project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/drf/drf_testing/project/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for project 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/3.2/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', 'project.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_minimal/config/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for config project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_minimal/config/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for config 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/3.2/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', 'config.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_celery_worker/mysite/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for mysite project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_celery_worker/mysite/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for mysite 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/3.2/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', 'mysite.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/config/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for config project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/config/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for config 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/3.2/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', 'config.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/mysite/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for mysite project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/mysite/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for mysite 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/3.2/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', 'mysite.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/test_models.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from model_bakery import baker
3 | from shop.models import Customer
4 |
5 |
6 | @pytest.fixture
7 | def customer():
8 | """Fixture for baked Customer model."""
9 | return baker.make(Customer)
10 |
11 |
12 | @pytest.mark.django_db
13 | def test_using_customer(customer):
14 | """Test function using fixture of baked model."""
15 | print(customer.name)
16 | print(customer.email)
17 | print(customer.age)
18 | assert isinstance(customer, Customer)
19 |
--------------------------------------------------------------------------------
/test/cors/static/js/test_google.js:
--------------------------------------------------------------------------------
1 | function main()
2 | {
3 | (function() {
4 | const httpRequest = new XMLHttpRequest();
5 | httpRequest.onreadystatechange = logContents;
6 | httpRequest.open('GET', 'https://google.com');
7 | httpRequest.send();
8 | function logContents() {
9 | if (httpRequest.readyState === XMLHttpRequest.DONE) {
10 | console.log(httpRequest.status);
11 | console.log(httpRequest.responseText);
12 | }
13 | }
14 | })();
15 | }
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/models/user.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import Boolean, Column, String
2 | from sqlalchemy.dialects.mysql import INTEGER
3 | from app.db.session import Base
4 |
5 |
6 | class User(Base):
7 | __tablename__ = "user"
8 |
9 | id = Column(INTEGER(display_width=11, unsigned=True), primary_key=True, index=True)
10 | email = Column(String(255), unique=True, index=True)
11 | password = Column(String(255))
12 | is_active = Column(Boolean, default=True)
13 | is_superuser = Column(Boolean(), default=False)
14 |
--------------------------------------------------------------------------------
/drf/drf_testing/README.md:
--------------------------------------------------------------------------------
1 | # DRF(Django REST framework) Testing
2 | Reference:
3 | - [DRF Testing](https://www.django-rest-framework.org/api-guide/testing/)
4 |
5 | This example is using [DRF CRUD](https://github.com/taptorestart/python-backend-examples/tree/main/drf/drf_crud).
6 |
7 |
8 | ## Install
9 | ```shell
10 | $ python3 -m venv venv
11 | $ source ./venv/bin/activate
12 | $ pip install -r requirements.txt
13 | ```
14 |
15 |
16 | ## Test
17 | ```shell
18 | $ python manage.py test
19 | ```
20 |
21 | Result
22 |
23 | 
24 |
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI, Request
2 | from fastapi.responses import HTMLResponse
3 | from fastapi.staticfiles import StaticFiles
4 | from fastapi.templating import Jinja2Templates
5 |
6 | app = FastAPI()
7 | app.mount("/static", StaticFiles(directory="static"), name="static")
8 | templates = Jinja2Templates(directory="templates")
9 |
10 |
11 | @app.get("/items/{id}", response_class=HTMLResponse)
12 | async def read_item(request: Request, id: str):
13 | return templates.TemplateResponse("item.html", {"request": request, "id": id})
14 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/db/session.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import create_engine
2 | from sqlalchemy.ext.declarative import declarative_base
3 | from sqlalchemy.orm import sessionmaker
4 | from app.core.config import settings
5 |
6 |
7 | engine = create_engine(settings.SQLALCHEMY_DATABASE_URL)
8 | SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
9 |
10 | Base = declarative_base()
11 |
12 |
13 | # Dependency
14 | def get_db():
15 | db = SessionLocal()
16 | try:
17 | yield db
18 | finally:
19 | db.close()
20 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/database.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import create_engine
2 | from sqlalchemy.ext.declarative import declarative_base
3 | from sqlalchemy.orm import sessionmaker
4 |
5 | # Database connection
6 | username = 'admin'
7 | password = 'verysecret'
8 | host = 'localhost'
9 | port = 3306
10 | database = 'your_database'
11 |
12 | SQLALCHEMY_DATABASE_URL = f'mysql://{username}:{password}@{host}:{port}/{database}'
13 |
14 | engine = create_engine(SQLALCHEMY_DATABASE_URL)
15 | SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
16 |
17 | Base = declarative_base()
18 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 |
4 | class Category(models.Model):
5 | name = models.CharField(max_length=200)
6 | created_at = models.DateTimeField(auto_now_add=True)
7 | updated_at = models.DateTimeField(auto_now=True)
8 |
9 |
10 | class Beverage(models.Model):
11 | name = models.CharField(max_length=200)
12 | category = models.ForeignKey(Category, on_delete=models.CASCADE)
13 | price = models.IntegerField()
14 | created_at = models.DateTimeField(auto_now_add=True)
15 | updated_at = models.DateTimeField(auto_now=True)
16 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Upload Test
6 |
7 |
8 | File Upload Test
9 |
10 | Upload Test
11 |
12 |
13 | Upload Test with simple button
14 |
15 |
16 | Upload Test with secure filename
17 |
18 |
19 |
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
7 |
8 |
21 |
22 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/db/init_db.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy.orm import Session
2 |
3 | from app.crud.user import crud_user
4 | from app.schemas.user import UserCreate
5 | from app.core.config import settings
6 |
7 |
8 | def init_db(db: Session) -> None:
9 | user = crud_user.get_by_email(db, email=settings.FIRST_SUPERUSER_EMAIL)
10 | if not user:
11 | user_in = UserCreate(
12 | email=settings.FIRST_SUPERUSER_EMAIL,
13 | password=settings.FIRST_SUPERUSER_PASSWORD,
14 | is_superuser=True
15 | )
16 | crud_user.create_superuser(db=db, obj_in=user_in)
17 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 |
4 | class Category(models.Model):
5 | name = models.CharField(max_length=200)
6 | created_at = models.DateTimeField(auto_now_add=True)
7 | updated_at = models.DateTimeField(auto_now=True)
8 |
9 |
10 | class Beverage(models.Model):
11 | name = models.CharField(max_length=200)
12 | category = models.ForeignKey(Category, on_delete=models.CASCADE)
13 | price = models.IntegerField()
14 | is_available = models.BooleanField(default=False)
15 | created_at = models.DateTimeField(auto_now_add=True)
16 | updated_at = models.DateTimeField(auto_now=True)
17 |
--------------------------------------------------------------------------------
/drf/drf_minimal/app/views.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import viewsets
3 | from rest_framework import permissions
4 | from app.serializers import UserSerializer, GroupSerializer
5 |
6 |
7 | class UserViewSet(viewsets.ModelViewSet):
8 | queryset = User.objects.all().order_by('-date_joined')
9 | serializer_class = UserSerializer
10 | permission_classes = [permissions.IsAuthenticated]
11 |
12 |
13 | class GroupViewSet(viewsets.ModelViewSet):
14 | queryset = Group.objects.all()
15 | serializer_class = GroupSerializer
16 | permission_classes = [permissions.IsAuthenticated]
17 |
--------------------------------------------------------------------------------
/drf/drf_swagger/app/views.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import viewsets
3 | from rest_framework import permissions
4 | from app.serializers import UserSerializer, GroupSerializer
5 |
6 |
7 | class UserViewSet(viewsets.ModelViewSet):
8 | queryset = User.objects.all().order_by('-date_joined')
9 | serializer_class = UserSerializer
10 | permission_classes = [permissions.IsAuthenticated]
11 |
12 |
13 | class GroupViewSet(viewsets.ModelViewSet):
14 | queryset = Group.objects.all()
15 | serializer_class = GroupSerializer
16 | permission_classes = [permissions.IsAuthenticated]
17 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 |
4 | class Category(models.Model):
5 | name = models.CharField(max_length=200)
6 | created_at = models.DateTimeField(auto_now_add=True)
7 | updated_at = models.DateTimeField(auto_now=True)
8 |
9 |
10 | class Beverage(models.Model):
11 | name = models.CharField(max_length=200)
12 | category = models.ForeignKey(Category, on_delete=models.CASCADE)
13 | price = models.IntegerField()
14 | is_available = models.BooleanField(default=False)
15 | created_at = models.DateTimeField(auto_now_add=True)
16 | updated_at = models.DateTimeField(auto_now=True)
17 |
--------------------------------------------------------------------------------
/test/cors/app_ssl.py:
--------------------------------------------------------------------------------
1 | import ssl
2 |
3 | from flask import Flask, render_template
4 |
5 | context = ssl.SSLContext()
6 | pem = "/Users/taptorestart/local.taptorestart.com.pem" # Set your pem file path
7 | key = "/Users/taptorestart/local.taptorestart.com-key.pem" # Set your key pem file path
8 | context.load_cert_chain(pem, key)
9 |
10 |
11 | app = Flask(__name__)
12 |
13 |
14 | @app.route('/')
15 | def index():
16 | return render_template('index.html')
17 |
18 |
19 | HOST = 'local.taptorestart.com'
20 | PORT = 8000
21 |
22 |
23 | if __name__ == '__main__':
24 | app.run(host=HOST, port=PORT, debug=True, ssl_context=context)
25 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/schemas/user.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 | from pydantic import BaseModel, EmailStr
3 |
4 |
5 | class UserBase(BaseModel):
6 | email: EmailStr
7 | is_active: Optional[bool] = True
8 | is_superuser: Optional[bool] = False
9 |
10 |
11 | class UserCreate(UserBase):
12 | password: str
13 |
14 |
15 | class UserUpdate(UserBase):
16 | password: Optional[str] = None
17 |
18 |
19 | class UserInDBBase(UserBase):
20 | id: int
21 | password: Optional[str] = None
22 |
23 | class Config:
24 | orm_mode = True
25 |
26 |
27 | class UserRead(UserInDBBase):
28 | pass
29 |
--------------------------------------------------------------------------------
/fastapi/fastapi_api_router/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI API Router project example
2 | Source: [tiangolo / full-stack-fastapi-postgresql](https://github.com/tiangolo/full-stack-fastapi-postgresql)
3 |
4 | ## Environments
5 | Python v3.8.2
6 |
7 | ## Install
8 | ```shell
9 | $ mkdir fastapi_api_router
10 | $ cd fastapi_api_router
11 | $ python3 -m venv venv
12 | $ source ./venv/bin/activate
13 | $ pip install fastapi==0.74.1
14 | $ pip install "uvicorn[standard]"
15 | ```
16 |
17 | ## Run
18 | ```shell
19 | $ uvicorn main:app --reload
20 | ```
21 |
22 | ## Screenshots
23 | 
24 | 
25 |
--------------------------------------------------------------------------------
/test/cors/static/js/test_get_by_token.js:
--------------------------------------------------------------------------------
1 | function main()
2 | {
3 | (function() {
4 | var httpRequest = new XMLHttpRequest();
5 | httpRequest.onreadystatechange = logContents;
6 | httpRequest.open('GET', 'https://api.taptorestart.com/v1/test/');
7 | httpRequest.setRequestHeader('Authorization', 'Bearer yourtoken');
8 | httpRequest.send();
9 | function logContents() {
10 | if (httpRequest.readyState === XMLHttpRequest.DONE) {
11 | console.log(httpRequest.status);
12 | console.log(httpRequest.responseText);
13 | }
14 | }
15 | })();
16 | }
17 |
--------------------------------------------------------------------------------
/flask/flask_minimal/README.md:
--------------------------------------------------------------------------------
1 | # Flask minimal project
2 |
3 | ## Install
4 | ```shell
5 | mkdir flask_minimal
6 | cd flask_minimal
7 | python3 -m venv venv
8 | source ./venv/bin/activate
9 | pip install Flask==2.0.1
10 | ```
11 |
12 | ## Make file app.py
13 | Type below codes.
14 |
15 | ```python
16 | from flask import Flask
17 |
18 | app = Flask(__name__)
19 |
20 |
21 | @app.route('/')
22 | def hello():
23 | return 'Hello World!'
24 | ```
25 |
26 | ## Run
27 | ```shell
28 | export FLASK_ENV=development
29 | flask run
30 | ```
31 |
32 | That's all.
33 | Open your browser, and type url 'http://127.0.0.1:5000/'.
34 |
35 | 
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/user_client.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | import logging
4 |
5 | import grpc
6 | import user_pb2
7 | import user_pb2_grpc
8 |
9 |
10 | def run():
11 | with grpc.insecure_channel('localhost:50051') as channel:
12 | stub = user_pb2_grpc.UserServiceStub(channel)
13 | user = stub.GetUser(user_pb2.UserRequest(email='taptorestart@gmail.com'))
14 | print(f'user.id: {user.id}')
15 | print(f'user.email: {user.email}')
16 | print(f'user.is_active: {user.is_active}')
17 | print(f'user.is_superuser: {user.is_superuser}')
18 |
19 |
20 | if __name__ == '__main__':
21 | logging.basicConfig()
22 | run()
23 |
--------------------------------------------------------------------------------
/fastapi/fastapi_dependencies_first_steps/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Dependencies First Steps project example
2 | Source: [Dependencies - First Steps](https://fastapi.tiangolo.com/tutorial/dependencies)
3 |
4 | ## Environments
5 | Python v3.8.2
6 |
7 | ## Install
8 | ```shell
9 | $ mkdir fastapi_dependencies_first_steps
10 | $ cd fastapi_dependencies_first_steps
11 | $ python3 -m venv venv
12 | $ source ./venv/bin/activate
13 | $ pip install fastapi==0.74.1
14 | $ pip install "uvicorn[standard]"
15 | ```
16 |
17 | ## Run
18 | ```shell
19 | $ uvicorn main:app --reload
20 | ```
21 |
22 | ## Screenshots
23 | 
24 |
25 | 
26 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/schemas.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional
2 | from pydantic import BaseModel
3 |
4 |
5 | class ItemBase(BaseModel):
6 | title: str
7 | description: Optional[str] = None
8 |
9 |
10 | class ItemCreate(ItemBase):
11 | pass
12 |
13 |
14 | class Item(ItemBase):
15 | id: int
16 | owner_id: int
17 |
18 | class Config:
19 | orm_mode = True
20 |
21 |
22 | class UserBase(BaseModel):
23 | email: str
24 |
25 |
26 | class UserCreate(UserBase):
27 | password: str
28 |
29 |
30 | class User(UserBase):
31 | id: int
32 | is_active: bool
33 | items: List[Item] = []
34 |
35 | class Config:
36 | orm_mode = True
37 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/schemas.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional
2 | from pydantic import BaseModel
3 |
4 |
5 | class ItemBase(BaseModel):
6 | title: str
7 | description: Optional[str] = None
8 |
9 |
10 | class ItemCreate(ItemBase):
11 | pass
12 |
13 |
14 | class Item(ItemBase):
15 | id: int
16 | owner_id: int
17 |
18 | class Config:
19 | orm_mode = True
20 |
21 |
22 | class UserBase(BaseModel):
23 | email: str
24 |
25 |
26 | class UserCreate(UserBase):
27 | password: str
28 |
29 |
30 | class User(UserBase):
31 | id: int
32 | is_active: bool
33 | items: List[Item] = []
34 |
35 | class Config:
36 | orm_mode = True
37 |
--------------------------------------------------------------------------------
/fastapi/fastapi_path_parameters/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Path Parameters project example
2 |
3 | source: [FastAPI Tutorial - Path Parameters](https://fastapi.tiangolo.com/tutorial/path-params/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_path_parameters
13 | $ cd fastapi_path_parameters
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install fastapi==0.74.1
17 | $ pip install "uvicorn[standard]"
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | ## Screenshots
26 | 
27 |
28 | 
29 |
--------------------------------------------------------------------------------
/flask/flask_ajax/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template, request
2 |
3 | app = Flask(__name__)
4 |
5 |
6 | @app.route('/')
7 | def index():
8 | return render_template('index.html')
9 |
10 |
11 | @app.route('/get_image')
12 | def get_image():
13 | parameter_dict = request.args.to_dict()
14 | print(parameter_dict['id'])
15 | image_id = parameter_dict['id']
16 | image_filename = "01_result.jpg"
17 | if image_id == "image1":
18 | image_filename = "01_result.jpg"
19 | elif image_id == "image2":
20 | image_filename = "02_result.jpg"
21 | return render_template('ajax_image.html', image_filename=image_filename)
22 |
23 |
24 | if __name__ == '__main__':
25 | app.run()
26 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI orm project example
2 |
3 | source: [FastAPI Tutorial - SQL Databases](https://fastapi.tiangolo.com/tutorial/sql-databases/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_orm_sqlite
13 | $ cd fastapi_orm_sqlite
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install fastapi==0.74.1
17 | $ pip install "uvicorn[standard]"
18 | $ pip install -r requirements.txt
19 | ```
20 |
21 | ## Copy files
22 | Files' source: https://fastapi.tiangolo.com/tutorial/sql-databases/
23 |
24 | ## Run
25 | ```shell
26 | $ uvicorn main:app --reload
27 | ```
28 |
29 | Open your browser at http://127.0.0.1:8000/docs
30 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/shop/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.2.8 on 2022-01-13 10:13
2 |
3 | from django.db import migrations, models
4 |
5 |
6 | class Migration(migrations.Migration):
7 |
8 | initial = True
9 |
10 | dependencies = [
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Customer',
16 | fields=[
17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18 | ('name', models.CharField(max_length=30)),
19 | ('email', models.EmailField(max_length=254)),
20 | ('age', models.IntegerField()),
21 | ],
22 | ),
23 | ]
24 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_body/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Request Body project example
2 |
3 | source: [FastAPI Tutorial - Request Body](https://fastapi.tiangolo.com/tutorial/body/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_request_body
13 | $ cd fastapi_request_body
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install "uvicorn[standard]"
17 | $ pip install -r requirements.txt
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | ## Screenshots
26 |
27 | Read the body of the request as JSON
28 |
29 | 
30 |
31 | 
32 |
--------------------------------------------------------------------------------
/test/cors/static/js/test_post_by_token.js:
--------------------------------------------------------------------------------
1 | function main()
2 | {
3 | (function() {
4 | const httpRequest = new XMLHttpRequest();
5 | const data = "{ }";
6 | httpRequest.onreadystatechange = logContents;
7 | httpRequest.open('POST', 'https://api.taptorestart.com/v1/test/');
8 | httpRequest.setRequestHeader('Authorization', 'Bearer yourtoken');
9 | httpRequest.setRequestHeader('Content-Type', 'application/json');
10 | httpRequest.send(data);
11 | function logContents() {
12 | if (httpRequest.readyState === XMLHttpRequest.DONE) {
13 | console.log(httpRequest.status);
14 | console.log(httpRequest.responseText);
15 | }
16 | }
17 | })();
18 | }
--------------------------------------------------------------------------------
/drf/drf_crud/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/fastapi/fastapi_minimal/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI minimal project example
2 |
3 | source: [Fast API Tutorial - First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/)
4 |
5 | source license: MIT License
6 |
7 | ## Install
8 | ```shell
9 | $ mkdir fastapi_minimal
10 | $ cd fastapi_minimal
11 | $ python3 -m venv venv
12 | $ source ./venv/bin/activate
13 | $ pip install fastapi==0.74.1
14 | $ pip install "uvicorn[standard]"
15 | ```
16 |
17 | ## Make file main.py
18 | ```python
19 | from fastapi import FastAPI
20 |
21 | app = FastAPI()
22 |
23 |
24 | @app.get("/")
25 | async def root():
26 | return {"message": "Hello World"}
27 | ```
28 |
29 | ## Run
30 | ```shell
31 | $ uvicorn main:app --reload
32 | ```
33 |
34 | Open your browser at http://127.0.0.1:8000
35 |
--------------------------------------------------------------------------------
/drf/drf_minimal/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/drf/drf_swagger/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/drf/drf_testing/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django/django_minimal/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django/django_celery_worker/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI oauth2 project example
2 |
3 | source: [FastAPI Tutorial - Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_oauth2
13 | $ cd fastapi_oauth2
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install "uvicorn[standard]"
17 | $ pip install -r requirements.txt
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | ## screenshots
26 |
27 | 
28 | 
29 | 
30 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/serializers.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import serializers
3 | from app.models import Category, Beverage
4 |
5 |
6 | class UserSerializer(serializers.HyperlinkedModelSerializer):
7 | class Meta:
8 | model = User
9 | fields = ['url', 'username', 'email', 'groups']
10 |
11 |
12 | class GroupSerializer(serializers.HyperlinkedModelSerializer):
13 | class Meta:
14 | model = Group
15 | fields = ['url', 'name']
16 |
17 |
18 | class CategorySerializer(serializers.ModelSerializer):
19 | class Meta:
20 | model = Category
21 | fields = '__all__'
22 |
23 |
24 | class BeverageSerializer(serializers.ModelSerializer):
25 | class Meta:
26 | model = Beverage
27 | fields = '__all__'
28 |
--------------------------------------------------------------------------------
/test/cors/static/js/test_post_by_session.js:
--------------------------------------------------------------------------------
1 | function main()
2 | {
3 | (function() {
4 | const httpRequest = new XMLHttpRequest();
5 | const data = "{ }";
6 | httpRequest.onreadystatechange = logContents;
7 | httpRequest.withCredentials = true;
8 | httpRequest.open('POST', 'https://api.taptorestart.com/v1/test/');
9 | httpRequest.setRequestHeader('Cookie', 'sessionid=yoursessionid;');
10 | httpRequest.setRequestHeader('Content-Type', 'application/json');
11 | httpRequest.send(data);
12 | function logContents() {
13 | if (httpRequest.readyState === XMLHttpRequest.DONE) {
14 | console.log(httpRequest.status);
15 | console.log(httpRequest.responseText);
16 | }
17 | }
18 | })();
19 | }
--------------------------------------------------------------------------------
/drf/drf_testing/app/serializers.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import serializers
3 | from app.models import Category, Beverage
4 |
5 |
6 | class UserSerializer(serializers.HyperlinkedModelSerializer):
7 | class Meta:
8 | model = User
9 | fields = ['url', 'username', 'email', 'groups']
10 |
11 |
12 | class GroupSerializer(serializers.HyperlinkedModelSerializer):
13 | class Meta:
14 | model = Group
15 | fields = ['url', 'name']
16 |
17 |
18 | class CategorySerializer(serializers.ModelSerializer):
19 | class Meta:
20 | model = Category
21 | fields = '__all__'
22 |
23 |
24 | class BeverageSerializer(serializers.ModelSerializer):
25 | class Meta:
26 | model = Beverage
27 | fields = '__all__'
28 |
--------------------------------------------------------------------------------
/flask/flask_ajax/README.md:
--------------------------------------------------------------------------------
1 | # Flask ajax example
2 |
3 | ## Install
4 | ```shell
5 | mkdir flask_ajax
6 | cd flask_ajax
7 | python3 -m venv venv
8 | source ./venv/bin/activate
9 | pip install Flask==2.0.1
10 | ```
11 |
12 | ## Run
13 | ```shell
14 | export FLASK_ENV=development
15 | flask run
16 | ```
17 |
18 | ## source of images
19 | - 01.jpg source: [pixabay](https://pixabay.com/photos/apple-red-fruit-food-fresh-ripe-1834639/)
20 | - 01_result.jpg source: [pixabay](https://pixabay.com/photos/iphone-smartphone-apps-apple-inc-410324/)
21 | - 02.jpg source: [pixabay](https://pixabay.com/illustrations/robot-machine-technology-modern-6654029/)
22 | - 02_result.jpg source: [pixabay](https://pixabay.com/photos/samsung-smartphone-phone-technology-5188631/)
23 |
24 | ## screenshots
25 | 
26 | 
--------------------------------------------------------------------------------
/django/django_minimal/config/urls.py:
--------------------------------------------------------------------------------
1 | """config URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.2/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
18 |
19 | urlpatterns = [
20 | path('admin/', admin.site.urls),
21 | ]
22 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/models.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
2 | from sqlalchemy.orm import relationship
3 | from database import Base
4 |
5 |
6 | class User(Base):
7 | __tablename__ = "users"
8 |
9 | id = Column(Integer, primary_key=True, index=True)
10 | email = Column(String, unique=True, index=True)
11 | hashed_password = Column(String)
12 | is_active = Column(Boolean, default=True)
13 |
14 | items = relationship("Item", back_populates="owner")
15 |
16 |
17 | class Item(Base):
18 | __tablename__ = "items"
19 |
20 | id = Column(Integer, primary_key=True, index=True)
21 | title = Column(String, index=True)
22 | description = Column(String, index=True)
23 | owner_id = Column(Integer, ForeignKey("users.id"))
24 |
25 | owner = relationship("User", back_populates="items")
26 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/mysite/urls.py:
--------------------------------------------------------------------------------
1 | """mysite URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.2/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
18 |
19 | urlpatterns = [
20 | path('admin/', admin.site.urls),
21 | ]
22 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI oauth2 jwt project example
2 |
3 | source: [FastAPI Tutorial - OAuth2 with Password (and hashing), Bearer with JWT tokens](https://fastapi.tiangolo.com/ko/tutorial/security/oauth2-jwt/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_oauth2_jwt
13 | $ cd fastapi_oauth2_jwt
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install "uvicorn[standard]"
17 | $ pip install "passlib[bcrypt]"
18 | $ pip install -r requirements.txt
19 | ```
20 |
21 | ## Run
22 | ```shell
23 | $ uvicorn main:app --reload
24 | ```
25 |
26 | ## screenshots
27 |
28 | 
29 | 
30 | 
31 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/config/urls.py:
--------------------------------------------------------------------------------
1 | """config URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.2/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
18 |
19 |
20 | urlpatterns = [
21 | path('admin/', admin.site.urls),
22 | ]
23 |
--------------------------------------------------------------------------------
/fastapi/fastapi_cache_redis/main.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import time
3 |
4 | from fastapi import FastAPI
5 | import redis
6 | import json
7 |
8 | app = FastAPI()
9 | r = redis.Redis(host='localhost', port=6379, db=0)
10 |
11 |
12 | def get_response(endpoint):
13 | message = {"message": "Hello World"}
14 | if r.get(endpoint) is None:
15 | time.sleep(1)
16 | r.set(name=endpoint, value=json.dumps(message), ex=datetime.timedelta(seconds=30))
17 | response = message
18 | else:
19 | message = r.get(endpoint).decode('utf-8')
20 | response = json.loads(message)
21 | return response
22 |
23 |
24 | @app.get("/")
25 | async def root():
26 | endpoint = '/'
27 | start_time = time.time()
28 | response = get_response(endpoint)
29 | process_time = time.time() - start_time
30 | print(f'process_time: {process_time}')
31 | return response
32 |
--------------------------------------------------------------------------------
/django/django_celery_worker/README.md:
--------------------------------------------------------------------------------
1 | # Django celery worker
2 |
3 | ## Install
4 | ```shell
5 | python3 -m venv venv
6 | source venv/bin/activate
7 | python -m pip install django==3.2.8
8 | python -m django startproject mysite
9 | python manage.py startapp task
10 | ```
11 |
12 | install redis on Mac
13 | ```
14 | $ brew install redis
15 | $ brew services start redis
16 | $ redis-server
17 | ```
18 |
19 | ## Run
20 |
21 | ```shell
22 | python manage.py runserver
23 | ```
24 |
25 | run celery on the other terminal window
26 | ```shell
27 | celery -A mysite worker -l info
28 | ```
29 |
30 | ## Test
31 |
32 | POST example
33 | ```
34 | http://127.0.0.1:8000/tasks/
35 |
36 | {
37 | "number1": 3,
38 | "number2": 4
39 | }
40 | ```
41 | 
42 |
43 | GET example
44 | ```
45 | http://127.0.0.1:8000/tasks/?task_id=562b9626-4f41-407f-a1f4-e155b53f3290
46 | ```
47 | 
48 |
--------------------------------------------------------------------------------
/django/django_celery_worker/mysite/urls.py:
--------------------------------------------------------------------------------
1 | """mysite URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.2/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
18 | from task.views import TaskView
19 |
20 | urlpatterns = [
21 | path('admin/', admin.site.urls),
22 | path('tasks/', TaskView.as_view()),
23 | ]
24 |
--------------------------------------------------------------------------------
/django/django_minimal/README.md:
--------------------------------------------------------------------------------
1 | # Django minimal
2 |
3 | [mdn: Django introduction](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction)
4 |
5 | Source: [Writing your first Django app, part 1](https://docs.djangoproject.com/en/3.2/intro/tutorial01/)
6 |
7 |
8 | ## Test Environments
9 | Python v3.8.2
10 | MacOS v12.2.1
11 | Django v3.2.12
12 |
13 | ## Install
14 | ```shell
15 | $ mkdir django_minimal
16 | $ cd django_minimal
17 | $ python3 -m venv venv
18 | $ source ./venv/bin/activate
19 | $ pip install django==3.2.12
20 | ```
21 |
22 | Set up a new project. Please don't forget write '.'.
23 | ```shell
24 | $ django-admin startproject config .
25 | ```
26 |
27 | ## Migration
28 | ```shell
29 | $ python manage.py migrate
30 | ```
31 |
32 | ## Run
33 | ```shell
34 | $ python manage.py runserver
35 | ```
36 |
37 | ## Screenshots
38 | Open your browser at 127.0.0.1:8000/
39 |
40 | 
41 |
--------------------------------------------------------------------------------
/fastapi/fastapi_form_data/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Form Data project example
2 |
3 | source: [FastAPI Tutorial - Form Data](https://fastapi.tiangolo.com/tutorial/request-forms/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_form_data
13 | $ cd fastapi_form_data
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install -r requirements.txt
17 | $ pip install "uvicorn[standard]"
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | Open the login.html and input username and password.
26 | Or use a client program like Postman.
27 |
28 | ## Screenshots
29 | 
30 |
31 | 
32 |
33 | 
34 |
35 | 
36 |
37 | 
38 |
--------------------------------------------------------------------------------
/fastapi/fastapi_docker/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Docker
2 | source: [FastAPI in Containers - Docker](https://fastapi.tiangolo.com/deployment/docker/), MIT License
3 |
4 | ## Test Environments
5 | Python v3.8.2
6 | MacOS v12.2.1
7 | Docker v20.10.11
8 |
9 | ## Install
10 | ```shell
11 | $ mkdir fastapi_docker
12 | $ cd fastapi_docker
13 | ```
14 |
15 | ## Run
16 | ```shell
17 | $ uvicorn main:app --reload
18 | ```
19 |
20 | ## Docker build and run
21 | ```shell
22 | # bukld
23 | $ docker build . -t fastapi-docker
24 | $ docker run -d --name fastapi-app -p 8000:80 fastapi-docker
25 | ```
26 |
27 | ## Screenshots
28 | Run "docker build . -t fastapi-docker", then you can see the image.
29 |
30 | 
31 |
32 | Run "docker run -d --name fastapi-app -p 8000:80 fastapi-docker", then you can see the app.
33 |
34 | Click open in browser.
35 | 
36 |
37 | See the result.
38 |
39 | 
40 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/templates/upload.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
20 |
21 |
22 | File Upload Test
23 |
24 | Upload
25 |
26 |
27 |
28 |
29 | Uploaded file!
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Testing project example
2 |
3 | source: [FastAPI Tutorial - Testing](https://fastapi.tiangolo.com/tutorial/testing/)
4 |
5 | source license: MIT License
6 |
7 | ## Test Environments
8 | Python v3.8.2
9 | MacOS v12.2.1
10 |
11 | ## Install
12 | ```shell
13 | $ mkdir fastapi_testing
14 | $ cd fastapi_testing
15 | $ python3 -m venv venv
16 | $ source ./venv/bin/activate
17 | $ pip install "uvicorn[standard]"
18 | $ pip install -r requirements.txt
19 | ```
20 |
21 | ## Using pytest
22 | You need to install requests for pytest.
23 | ```shell
24 | $ pip install requests==2.27.1
25 | ```
26 |
27 | ## Run
28 | When you just run pytest, there will be some errors like below
29 | ```
30 | from fastapi.testclient import TestClient
31 | E ModuleNotFoundError: No module named 'fastapi'
32 | ```
33 | 
34 |
35 | You must run 'python -m pytest'.
36 |
37 | ```shell
38 | $ python -m pytest
39 | ```
40 |
41 | 
42 |
43 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/core/config.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from dotenv import load_dotenv
4 | from pydantic import BaseSettings, EmailStr
5 |
6 | load_dotenv()
7 |
8 |
9 | class Settings(BaseSettings):
10 | API_V1_STR: str = "/api/v1"
11 | SECRET_KEY: str = os.getenv('SECRET_KEY')
12 | ALGORITHM: str = "HS256"
13 | # 60 minutes * 24 hours * 7 days = 7 days
14 | ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7
15 |
16 | # Database connection
17 | HOST: str = os.getenv('HOST')
18 | PORT: int = os.getenv('PORT')
19 | USERNAME: str = os.getenv('USERNAME')
20 | PASSWORD: str = os.getenv('PASSWORD')
21 | DATABASE: str = os.getenv('DATABASE')
22 | FIRST_SUPERUSER_EMAIL: EmailStr = os.getenv('FIRST_SUPERUSER_EMAIL')
23 | FIRST_SUPERUSER_PASSWORD: str = os.getenv('FIRST_SUPERUSER_PASSWORD')
24 | SQLALCHEMY_DATABASE_URL = f'mysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}'
25 |
26 | class Config:
27 | case_sensitive = True
28 |
29 |
30 | settings = Settings()
31 |
--------------------------------------------------------------------------------
/fastapi/fastapi_static/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Static Files
2 |
3 | source: [Fast API Tutorial - Static Files](https://fastapi.tiangolo.com/tutorial/static-files/)
4 |
5 | source license: MIT License
6 |
7 | ## Install
8 | ```shell
9 | $ mkdir fastapi_static
10 | $ cd fastapi_static
11 | $ python3 -m venv venv
12 | $ source ./venv/bin/activate
13 | $ pip install fastapi==0.74.1
14 | $ pip install "uvicorn[standard]"
15 | ```
16 |
17 | ## Run
18 | ```shell
19 | $ uvicorn main:app --reload
20 | ```
21 |
22 | Open your browser at http://127.0.0.1:8000/static/index.html
23 |
24 |
25 | ## Attention
26 | You should separate source files(/app) and static files(/static).
27 |
28 | ## Screenshots
29 |
30 | /index.html
31 |
32 | 
33 |
34 | View source
35 |
36 | 
37 |
38 | You can access /static/style.css
39 |
40 | 
41 |
42 | You can't access root.css
43 |
44 | 
45 |
--------------------------------------------------------------------------------
/test/rest_api/README.md:
--------------------------------------------------------------------------------
1 | # REST API E2E(End To End) Test example using requests
2 |
3 | ## Environments
4 | Python v3.8.2
5 |
6 | ## Install
7 | ```shell
8 | $ python3 -m venv venv
9 | $ source ./venv/bin/activate
10 | $ pip install -r requirements.txt
11 | ```
12 |
13 | ## Envrionment Variables example
14 |
15 | Create a .env file like below and save on your project directory where the README.md is.
16 | ```
17 | BASE_URL=http://localhost:8000
18 | ADMIN_EMAIL=taptorestart@gmail.com
19 | ADMIN_PASSWORD=verysecret
20 | ```
21 |
22 | ## Run
23 | You should run this [FastAPI example](https://github.com/taptorestart/python-backend-examples/tree/main/fastapi/fastapi_email_login_jwt_mysql).
24 | And then you can API E2E test.
25 |
26 | ```shell
27 | $ pytest
28 | ```
29 |
30 | ## Screenshots
31 |
32 | Result of pytest
33 |
34 | 
35 |
36 | User table before run
37 |
38 | 
39 |
40 | User table after run
41 |
42 | 
43 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/core/security.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime, timedelta
2 | from typing import Any, Union
3 |
4 | from jose import jwt
5 | from passlib.context import CryptContext
6 |
7 | from app.core.config import settings
8 |
9 | pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
10 |
11 |
12 | def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str:
13 | if expires_delta:
14 | expire = datetime.utcnow() + expires_delta
15 | else:
16 | expire = datetime.utcnow() + timedelta(
17 | minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
18 | )
19 | to_encode = {"exp": expire, "sub": str(subject)}
20 | encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
21 | return encoded_jwt
22 |
23 |
24 | def verify_password(plain_password: str, hashed_password: str) -> bool:
25 | return pwd_context.verify(plain_password, hashed_password)
26 |
27 |
28 | def get_password_hash(password: str) -> str:
29 | return pwd_context.hash(password)
30 |
--------------------------------------------------------------------------------
/fastapi/fastapi_cache_redis/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI cache with Redis example
2 |
3 | This example is using [FastAPI minimal](https://github.com/taptorestart/python-backend-examples/tree/main/fastapi/fastapi_minimal) example.
4 |
5 | This example is just to show why we need to use cache with in-memory database like Redis.
6 |
7 | Please find some good cache packages: [fastapi-redis-cache](https://github.com/a-luna/fastapi-redis-cache), [fastapi-cache](https://github.com/long2ice/fastapi-cache), etc.
8 |
9 | ## Install
10 | ```shell
11 | $ mkdir fastapi_redis
12 | $ cd fastapi_redis
13 | $ python3 -m venv venv
14 | $ source ./venv/bin/activate
15 | $ pip -r requirements.txt
16 | ```
17 |
18 | ## Install redis
19 | On MacOS
20 | ```shell
21 | $ brew install redis
22 | $ brew services start redis
23 | ```
24 |
25 | ## Run
26 | ```shell
27 | $ uvicorn main:app --reload
28 | ```
29 |
30 | Open your browser at http://127.0.0.1:8000
31 |
32 | ## Screenshots
33 | Test Result on My Mac mini(2018): Processor 3.2GHz 6-Core Intel Core i7, Memory 64GB
34 |
35 | 
36 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/templates/upload_test_with_secure_filename.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
20 |
21 |
22 | File Upload Test with secure filename
23 |
24 |
25 | Upload
26 |
27 |
28 |
29 |
30 | Uploaded file!
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/django/django_celery_worker/task/views.py:
--------------------------------------------------------------------------------
1 | from django.http import JsonResponse
2 | from celery.result import AsyncResult
3 | import json
4 | from django.views.generic import View
5 | from django.views.decorators.csrf import csrf_exempt
6 | from task.tasks import add
7 |
8 |
9 | class TaskView(View):
10 | @csrf_exempt
11 | def dispatch(self, *args, **kwargs):
12 | return super(TaskView, self).dispatch(*args, **kwargs)
13 |
14 | def post(self, request, *args, **kwargs):
15 | json_data = json.loads(request.body)
16 | number1 = json_data["number1"]
17 | number2 = json_data["number2"]
18 | task = add.delay(number1, number2)
19 | return JsonResponse({"task_id": task.id}, status=202)
20 |
21 | def get(self, request, *args, **kwargs):
22 | task_id = request.GET.get("task_id")
23 | task_result = AsyncResult(task_id)
24 | result = {
25 | "task_id": task_id,
26 | "task_status": task_result.status,
27 | "result": task_result.result
28 | }
29 | return JsonResponse(result, status=200)
--------------------------------------------------------------------------------
/fastapi/fastapi_query_parameters/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Query Parameters project example
2 |
3 | source: [FastAPI Tutorial - Query Parameters](https://fastapi.tiangolo.com/tutorial/query-params/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_query_parameters
13 | $ cd fastapi_query_parameters
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install fastapi==0.74.1
17 | $ pip install "uvicorn[standard]"
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | ## Guide
26 | When just add a parameter, it becomes a query parameter automatically.
27 | In the example below, skip and limit are query parameters.
28 | ```python
29 | @app.get("/items/")
30 | async def read_item(skip: int = 0, limit: int = 10):
31 | print(f'skip: {skip}')
32 | print(f'limit: {limit}')
33 | return fake_items_db[skip: skip + limit]
34 | ```
35 |
36 | ## Screenshots
37 | 
38 | 
39 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Request Files project example
2 |
3 | source: [FastAPI Tutorial - Request Files](https://fastapi.tiangolo.com/tutorial/request-files/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_request_files
13 | $ cd fastapi_request_files
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install -r requirements.txt
17 | $ pip install "uvicorn[standard]"
18 | ```
19 |
20 | ## Run
21 | ```shell
22 | $ uvicorn main:app --reload
23 | ```
24 |
25 | 1. Open browser at 'http://127.0.0.1:8000/'
26 | 2. Choose files
27 | 3. Submit!
28 |
29 | ## Screenshots
30 |
31 | 
32 |
33 | 
34 |
35 | ### Multiple files as bytes
36 | 
37 |
38 | You can't get bytes' filename.
39 | You must set new filename.
40 |
41 | ### Multiple files as UploadFile
42 | 
43 |
44 | You can get uploadfile's filename.
--------------------------------------------------------------------------------
/test/cors/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Test
6 |
7 |
8 |
9 |
15 |
16 |
17 |
18 |
19 | CORS Test
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 taptorestart
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.
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI orm with MySQL project example
2 |
3 | source: [FastAPI Tutorial - SQL Databases](https://fastapi.tiangolo.com/tutorial/sql-databases/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 | Mysql v5.7
10 |
11 | ## Install
12 | ```shell
13 | $ mkdir fastapi_orm_mysql
14 | $ cd fastapi_orm_mysql
15 | $ python3 -m venv venv
16 | $ source ./venv/bin/activate
17 | $ pip install fastapi==0.74.1
18 | $ pip install "uvicorn[standard]"
19 | ```
20 |
21 | ## Mysql
22 | You need import INTEGER.
23 | ```python
24 | from sqlalchemy.dialects.mysql import INTEGER
25 | ```
26 | If you want unsigned integer with length 11, you need to set model with "INTEGER(display_width=11, unsigned=True)".
27 | ```
28 | INTEGER: signed integer, length 11
29 | INTEGER(unsigned=True): unsigned integer, length 10
30 | INTEGER(display_width=11, unsigned=True): unsigned integer, length 11
31 | ```
32 |
33 | ## Run
34 | ```shell
35 | $ uvicorn main:app --reload
36 | ```
37 |
38 | Open your browser at http://127.0.0.1:8000/docs
39 |
40 | ## Screenshots
41 | 
42 | 
43 |
--------------------------------------------------------------------------------
/drf/drf_swagger/project/urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import include, path
2 | from rest_framework import routers
3 | from app import views
4 | from drf_yasg.views import get_schema_view
5 | from drf_yasg import openapi
6 | from rest_framework import permissions
7 | from django.urls import re_path
8 |
9 | # Swagger API
10 | schema_view = get_schema_view(
11 | openapi.Info(
12 | title="App API",
13 | default_version="v1",
14 | description="App API",
15 | ),
16 | public=True,
17 | permission_classes=(permissions.AllowAny,),
18 | )
19 |
20 | router = routers.DefaultRouter()
21 | router.register(r'users', views.UserViewSet)
22 | router.register(r'groups', views.GroupViewSet)
23 |
24 | urlpatterns = [
25 | path('', include(router.urls)),
26 | path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
27 | ]
28 |
29 | # swagger url
30 | urlpatterns += [
31 | re_path(r'^swagger(?P\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name="schema-json"),
32 | re_path(r'^swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
33 | re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
34 | ]
35 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/crud.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy.orm import Session
2 |
3 | import models
4 | import schemas
5 |
6 |
7 | def get_user(db: Session, user_id: int):
8 | return db.query(models.User).filter(models.User.id == user_id).first()
9 |
10 |
11 | def get_user_by_email(db: Session, email: str):
12 | return db.query(models.User).filter(models.User.email == email).first()
13 |
14 |
15 | def get_users(db: Session, skip: int = 0, limit: int = 100):
16 | return db.query(models.User).offset(skip).limit(limit).all()
17 |
18 |
19 | def create_user(db: Session, user: schemas.UserCreate):
20 | fake_hashed_password = user.password + "notreallyhashed"
21 | db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
22 | db.add(db_user)
23 | db.commit()
24 | db.refresh(db_user)
25 | return db_user
26 |
27 |
28 | def get_items(db: Session, skip: int = 0, limit: int = 100):
29 | return db.query(models.Item).offset(skip).limit(limit).all()
30 |
31 |
32 | def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
33 | db_item = models.Item(**item.dict(), owner_id=user_id)
34 | db.add(db_item)
35 | db.commit()
36 | db.refresh(db_item)
37 | return db_item
38 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/crud.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy.orm import Session
2 |
3 | import models
4 | import schemas
5 |
6 |
7 | def get_user(db: Session, user_id: int):
8 | return db.query(models.User).filter(models.User.id == user_id).first()
9 |
10 |
11 | def get_user_by_email(db: Session, email: str):
12 | return db.query(models.User).filter(models.User.email == email).first()
13 |
14 |
15 | def get_users(db: Session, skip: int = 0, limit: int = 100):
16 | return db.query(models.User).offset(skip).limit(limit).all()
17 |
18 |
19 | def create_user(db: Session, user: schemas.UserCreate):
20 | fake_hashed_password = user.password + "notreallyhashed"
21 | db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
22 | db.add(db_user)
23 | db.commit()
24 | db.refresh(db_user)
25 | return db_user
26 |
27 |
28 | def get_items(db: Session, skip: int = 0, limit: int = 100):
29 | return db.query(models.Item).offset(skip).limit(limit).all()
30 |
31 |
32 | def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
33 | db_item = models.Item(**item.dict(), owner_id=user_id)
34 | db.add(db_item)
35 | db.commit()
36 | db.refresh(db_item)
37 | return db_item
38 |
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/user_server.py:
--------------------------------------------------------------------------------
1 | from concurrent import futures
2 | import logging
3 |
4 | import grpc
5 | import user_pb2
6 | import user_pb2_grpc
7 |
8 | fake_users_db = {
9 | "taptorestart@gmail.com": {
10 | "id": 1,
11 | "email": "taptorestart@gmail.com",
12 | "is_active": 1,
13 | "is_superuser": 1
14 | },
15 | }
16 |
17 |
18 | class User(user_pb2_grpc.UserServiceServicer):
19 |
20 | def GetUser(self, request, context):
21 | email = request.email
22 | print(email)
23 | if email in fake_users_db:
24 | user_dict = fake_users_db[email]
25 | user = user_pb2.User()
26 | user.id = user_dict['id']
27 | user.email = user_dict['email']
28 | user.is_active = user_dict['is_active']
29 | user.is_superuser = user_dict['is_superuser']
30 | return user
31 |
32 |
33 | def serve():
34 | server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
35 | user_pb2_grpc.add_UserServiceServicer_to_server(User(), server)
36 | server.add_insecure_port('[::]:50051')
37 | server.start()
38 | server.wait_for_termination()
39 |
40 |
41 | if __name__ == '__main__':
42 | logging.basicConfig()
43 | serve()
44 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/views.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import viewsets
3 | from rest_framework import permissions
4 | from app.serializers import UserSerializer, GroupSerializer, CategorySerializer, BeverageSerializer
5 | from app.models import Category, Beverage
6 |
7 |
8 | class UserViewSet(viewsets.ModelViewSet):
9 | queryset = User.objects.all().order_by('-date_joined')
10 | serializer_class = UserSerializer
11 | permission_classes = [permissions.IsAuthenticated]
12 |
13 |
14 | class GroupViewSet(viewsets.ModelViewSet):
15 | queryset = Group.objects.all()
16 | serializer_class = GroupSerializer
17 | permission_classes = [permissions.IsAuthenticated]
18 |
19 |
20 | class CategoryViewSet(viewsets.ModelViewSet):
21 | queryset = Category.objects.all()
22 | serializer_class = CategorySerializer
23 | http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head']
24 | permission_classes = [permissions.IsAuthenticated]
25 |
26 |
27 | class BeverageViewSet(viewsets.ModelViewSet):
28 | queryset = Beverage.objects.all()
29 | serializer_class = BeverageSerializer
30 | http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head']
31 | permission_classes = [permissions.IsAuthenticated]
32 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/views.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import User, Group
2 | from rest_framework import viewsets
3 | from rest_framework import permissions
4 | from app.serializers import UserSerializer, GroupSerializer, CategorySerializer, BeverageSerializer
5 | from app.models import Category, Beverage
6 |
7 |
8 | class UserViewSet(viewsets.ModelViewSet):
9 | queryset = User.objects.all().order_by('-date_joined')
10 | serializer_class = UserSerializer
11 | permission_classes = [permissions.IsAuthenticated]
12 |
13 |
14 | class GroupViewSet(viewsets.ModelViewSet):
15 | queryset = Group.objects.all()
16 | serializer_class = GroupSerializer
17 | permission_classes = [permissions.IsAuthenticated]
18 |
19 |
20 | class CategoryViewSet(viewsets.ModelViewSet):
21 | queryset = Category.objects.all()
22 | serializer_class = CategorySerializer
23 | http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head']
24 | permission_classes = [permissions.IsAuthenticated]
25 |
26 |
27 | class BeverageViewSet(viewsets.ModelViewSet):
28 | queryset = Beverage.objects.all()
29 | serializer_class = BeverageSerializer
30 | http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head']
31 | permission_classes = [permissions.IsAuthenticated]
32 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/main_extended.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | from fastapi import FastAPI, Header, HTTPException
4 | from pydantic import BaseModel
5 |
6 | fake_secret_token = "coneofsilence"
7 |
8 | fake_db = {
9 | "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
10 | "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
11 | }
12 |
13 | app = FastAPI()
14 |
15 |
16 | class Item(BaseModel):
17 | id: str
18 | title: str
19 | description: Optional[str] = None
20 |
21 |
22 | @app.get("/items/{item_id}", response_model=Item)
23 | async def read_main(item_id: str, x_token: str = Header(...)):
24 | if x_token != fake_secret_token:
25 | raise HTTPException(status_code=400, detail="Invalid X-Token header")
26 | if item_id not in fake_db:
27 | raise HTTPException(status_code=404, detail="Item not found")
28 | return fake_db[item_id]
29 |
30 |
31 | @app.post("/items/", response_model=Item)
32 | async def create_item(item: Item, x_token: str = Header(...)):
33 | if x_token != fake_secret_token:
34 | raise HTTPException(status_code=400, detail="Invalid X-Token header")
35 | if item.id in fake_db:
36 | raise HTTPException(status_code=400, detail="Item already exists")
37 | fake_db[item.id] = item
38 | return item
39 |
--------------------------------------------------------------------------------
/flask/flask_orm/README.md:
--------------------------------------------------------------------------------
1 | # Flask ORM example project
2 |
3 | ## Install
4 | ```shell
5 | mkdir flask_orm
6 | cd flask_orm/
7 | python3 -m venv venv
8 | source venv/bin/activate
9 | pip install flask
10 | pip install flask_sqlalchemy
11 | ```
12 |
13 | ## Make sqlite database
14 | ```shell
15 | python init_db.py
16 | ```
17 |
18 | ## Check data
19 | ```shell
20 | python list.py
21 | ```
22 |
23 | Result
24 | ```
25 | id: 1
26 | name: Bulgogi
27 | price: 15000 WON
28 | id: 2
29 | name: Samgyeopsal
30 | price: 12000 WON
31 | id: 3
32 | name: Ddukbokki
33 | price: 4000 WON
34 | id: 4
35 | name: Bibimbap
36 | price: 8000 WON
37 | id: 5
38 | name: Seolleongtang
39 | price: 10000 WON
40 | ```
41 |
42 | ## Run
43 | ```shell
44 | export FLASK_ENV=development
45 | flask run
46 | ```
47 |
48 | ## References
49 | https://flask.palletsprojects.com/en/2.0.x/
50 | https://flask-sqlalchemy.palletsprojects.com/en/2.x/
51 |
52 | ## Test Example
53 |
54 | 
55 |
56 | 
57 |
58 | 
59 |
60 | 
61 |
62 | 
63 |
64 | 
65 |
66 | 
67 |
68 | 
--------------------------------------------------------------------------------
/django/django_admin_register_app/cafe/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.2.12 on 2022-03-26 23:06
2 |
3 | from django.db import migrations, models
4 | import django.db.models.deletion
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Category',
17 | fields=[
18 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 | ('name', models.CharField(max_length=200)),
20 | ('created_at', models.DateTimeField(auto_now_add=True)),
21 | ('updated_at', models.DateTimeField(auto_now=True)),
22 | ],
23 | ),
24 | migrations.CreateModel(
25 | name='Beverage',
26 | fields=[
27 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
28 | ('name', models.CharField(max_length=200)),
29 | ('price', models.IntegerField()),
30 | ('created_at', models.DateTimeField(auto_now_add=True)),
31 | ('updated_at', models.DateTimeField(auto_now=True)),
32 | ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cafe.category')),
33 | ],
34 | ),
35 | ]
36 |
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Response Model project example
2 |
3 | source: [FastAPI Tutorial - Response Model](https://fastapi.tiangolo.com/tutorial/response-model/)
4 |
5 | source license: MIT License
6 |
7 | ## Environments
8 | Python v3.8.2
9 |
10 | ## Install
11 | ```shell
12 | $ mkdir fastapi_response_model
13 | $ cd fastapi_response_model
14 | $ python3 -m venv venv
15 | $ source ./venv/bin/activate
16 | $ pip install "uvicorn[standard]"
17 | $ pip install "pydantic[email]"
18 | $ pip install -r requirements.txt
19 | ```
20 |
21 | ## Run
22 | ```shell
23 | $ uvicorn main:app --reload
24 | ```
25 |
26 | ## Screenshots
27 | ```python
28 | @app.post("/user/", response_model=UserOut)
29 | async def create_user(user: UserIn):
30 | ```
31 | 
32 |
33 | 
34 |
35 | ```python
36 | @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
37 | ```
38 | 
39 |
40 | 
41 |
42 | ```python
43 | @app.get("/items/{item_id}/name", response_model=Item, response_model_include={"name", "description"})
44 | ```
45 | 
46 |
47 | ```python
48 | @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={"tax"})
49 | ```
50 | 
51 |
--------------------------------------------------------------------------------
/drf/drf_crud/README.md:
--------------------------------------------------------------------------------
1 | # DRF(Django REST framework) CRUD
2 |
3 | ## Install
4 |
5 | ```shell
6 | $ python3 -m venv venv
7 | $ source ./venv/bin/activate
8 | $ pip install -r requirements.txt
9 | ```
10 |
11 | ## Migration
12 | ```shell
13 | $ python manage.py migrate
14 | ```
15 |
16 | ## Create admin user
17 | Please input admin's password.
18 | ```shell
19 | $ python manage.py createsuperuser --email admin@taptorestart.com --username admin
20 | Password: verysecret
21 | Password (again): verysecret
22 | ```
23 |
24 | ## Run
25 | ```shell
26 | $ python manage.py runserver
27 | ```
28 |
29 | ## Screenshots
30 |
31 | 127.0.0.1:8000/
32 |
33 | 
34 |
35 | 127.0.0.1:8000/categories
36 |
37 | 
38 |
39 | You need to login. Please click Log in button! And input your username and password.
40 |
41 | 
42 |
43 | Please add a coffee.
44 |
45 | 
46 |
47 | 127.0.0.1:8000/beverages
48 |
49 | Please add an americano.
50 |
51 | 
52 |
53 | 127.0.0.1:8000/beverages/1/
54 |
55 | You can delete, get, or put.
56 |
57 | 
58 |
59 | 127.0.0.1:8000/categories/1/
60 |
61 | You can delete, get, or put.
62 |
63 | 
64 |
65 |
--------------------------------------------------------------------------------
/drf/drf_crud/app/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.2.12 on 2022-04-29 04:49
2 |
3 | from django.db import migrations, models
4 | import django.db.models.deletion
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Category',
17 | fields=[
18 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 | ('name', models.CharField(max_length=200)),
20 | ('created_at', models.DateTimeField(auto_now_add=True)),
21 | ('updated_at', models.DateTimeField(auto_now=True)),
22 | ],
23 | ),
24 | migrations.CreateModel(
25 | name='Beverage',
26 | fields=[
27 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
28 | ('name', models.CharField(max_length=200)),
29 | ('price', models.IntegerField()),
30 | ('is_available', models.BooleanField(default=False)),
31 | ('created_at', models.DateTimeField(auto_now_add=True)),
32 | ('updated_at', models.DateTimeField(auto_now=True)),
33 | ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.category')),
34 | ],
35 | ),
36 | ]
37 |
--------------------------------------------------------------------------------
/drf/drf_testing/app/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.2.12 on 2022-04-29 04:49
2 |
3 | from django.db import migrations, models
4 | import django.db.models.deletion
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Category',
17 | fields=[
18 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 | ('name', models.CharField(max_length=200)),
20 | ('created_at', models.DateTimeField(auto_now_add=True)),
21 | ('updated_at', models.DateTimeField(auto_now=True)),
22 | ],
23 | ),
24 | migrations.CreateModel(
25 | name='Beverage',
26 | fields=[
27 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
28 | ('name', models.CharField(max_length=200)),
29 | ('price', models.IntegerField()),
30 | ('is_available', models.BooleanField(default=False)),
31 | ('created_at', models.DateTimeField(auto_now_add=True)),
32 | ('updated_at', models.DateTimeField(auto_now=True)),
33 | ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.category')),
34 | ],
35 | ),
36 | ]
37 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/models.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import Boolean, Column, Integer, ForeignKey, String
2 | from sqlalchemy.dialects.mysql import INTEGER
3 | from sqlalchemy.orm import relationship
4 | from database import Base
5 |
6 |
7 | '''
8 | # Default
9 | from sqlalchemy import Integer
10 | Integer: signed integer, length 11
11 |
12 | # MySQL
13 | from sqlalchemy.dialects.mysql import INTEGER
14 | INTEGER: signed integer, length 11
15 | INTEGER(unsigned=True): unsigned integer, length 10
16 | INTEGER(display_width=11, unsigned=True): unsigned integer, length 11
17 |
18 | source: https://docs.sqlalchemy.org/en/14/dialects/mysql.html?highlight=unsigned#sqlalchemy.dialects.mysql.INTEGER.params.unsigned
19 | '''
20 |
21 |
22 | class User(Base):
23 | __tablename__ = "users"
24 |
25 | id = Column(INTEGER(display_width=11, unsigned=True), primary_key=True, index=True)
26 | email = Column(String(255), unique=True, index=True)
27 | hashed_password = Column(String(255))
28 | is_active = Column(Boolean, default=True)
29 |
30 | items = relationship("Item", back_populates="owner")
31 |
32 |
33 | class Item(Base):
34 | __tablename__ = "items"
35 |
36 | id = Column(INTEGER(display_width=11, unsigned=True), primary_key=True, index=True)
37 | title = Column(String(255), index=True)
38 | description = Column(String(255), index=True)
39 | owner_id = Column(INTEGER(display_width=11, unsigned=True), ForeignKey("users.id"))
40 |
41 | owner = relationship("User", back_populates="items")
42 |
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/README.md:
--------------------------------------------------------------------------------
1 | # gRPC Simple Message Example
2 | Reference: [gRPC Quickstart](https://grpc.io/docs/languages/python/quickstart/)
3 |
4 | ## Test Environments
5 | - Python v3.8.2
6 | - MacOS v12.2.1
7 |
8 | ## Install
9 | ```shell
10 | $ python3 -m venv venv
11 | $ source venv/bin/activate
12 | $ pip install -r requirements.txt
13 | ```
14 |
15 | ## Make proto file user.proto
16 | ```
17 | syntax = "proto3";
18 |
19 | package grpc;
20 |
21 | service UserService {
22 | rpc GetUser (UserRequest) returns (User) {}
23 | }
24 |
25 | message User {
26 | int32 id = 1;
27 | string email = 2;
28 | int32 is_active = 3;
29 | int32 is_superuser = 4;
30 | }
31 |
32 | message UserRequest {
33 | string email = 1;
34 | }
35 | ```
36 |
37 | ###Make pb2 files for user.proto
38 |
39 | Format
40 | ```shell
41 | python -m grpc_tools.protoc -I {proto_file_directory} --python_out={python_output_file_directory} --grpc_python_out={grpc_python_output_file_directory} {proto_file_path}
42 | ```
43 |
44 | Example for user.proto
45 | ```shell
46 | python -m grpc_tools.protoc -I ./protos --python_out=. --grpc_python_out=. ./protos/user.proto
47 | ```
48 |
49 | ###Run server
50 | ```shell
51 | $ python user_server.py
52 | ```
53 | Result
54 | ```
55 | taptorestart@gmail.com
56 | ```
57 |
58 | ###Run client
59 | From another terminal, run the client
60 | ```shell
61 | $ python user_client.py
62 | ```
63 | Result
64 | ```
65 | user.id: 1
66 | user.email: taptorestart@gmail.com
67 | user.is_active: 1
68 | user.is_superuser: 1
69 | ```
70 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/templates/upload_simple_button.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Title
6 |
20 |
37 |
38 |
39 | File Upload Test
40 |
41 | Upload
42 |
43 |
44 |
45 |
46 | Uploaded file!
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/api_v1/endpoints/login.py:
--------------------------------------------------------------------------------
1 | from datetime import timedelta
2 |
3 | from fastapi import APIRouter, Depends, HTTPException, status
4 | from sqlalchemy.orm import Session
5 |
6 | from app.core.config import settings
7 | from app.core.security import create_access_token
8 | from app.db.session import Base, engine, get_db
9 | from app.schemas.user import UserCreate
10 | from app.crud.user import crud_user
11 |
12 | Base.metadata.create_all(bind=engine)
13 |
14 | router = APIRouter()
15 |
16 |
17 | @router.post("/register")
18 | def post(user: UserCreate, db: Session = Depends(get_db)):
19 | db_user = crud_user.get_by_email(db, email=user.email)
20 | if db_user:
21 | raise HTTPException(status_code=400, detail="Email already registered")
22 | return crud_user.create(db=db, obj_in=user)
23 |
24 |
25 | @router.post("/login/access-token")
26 | async def login_for_access_token(user: UserCreate, db: Session = Depends(get_db)):
27 | user = crud_user.authenticate(db=db, email=user.email, password=user.password)
28 | if not user:
29 | raise HTTPException(
30 | status_code=status.HTTP_401_UNAUTHORIZED,
31 | detail="Incorrect username or password",
32 | headers={"WWW-Authenticate": "Bearer"},
33 | )
34 | access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
35 | access_token = create_access_token(subject=user.email, expires_delta=access_token_expires)
36 | return {"access_token": access_token, "token_type": "bearer"}
37 |
--------------------------------------------------------------------------------
/fastapi/fastapi_response_model/main.py:
--------------------------------------------------------------------------------
1 | from typing import List, Optional
2 |
3 | from fastapi import FastAPI
4 | from pydantic import BaseModel, EmailStr
5 |
6 | app = FastAPI()
7 |
8 |
9 | class UserIn(BaseModel):
10 | username: str
11 | password: str
12 | email: EmailStr
13 | full_name: Optional[str] = None
14 |
15 |
16 | class UserOut(BaseModel):
17 | username: str
18 | email: EmailStr
19 | full_name: Optional[str] = None
20 |
21 |
22 | # Don't do this in production!
23 | @app.post("/user/", response_model=UserOut)
24 | async def create_user(user: UserIn):
25 | return user
26 |
27 |
28 | class Item(BaseModel):
29 | name: str
30 | description: Optional[str] = None
31 | price: float
32 | tax: float = 10.5
33 | tags: List[str] = []
34 |
35 |
36 | items = {
37 | "foo": {"name": "Foo", "price": 50.2},
38 | "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
39 | "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
40 | }
41 |
42 |
43 | @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
44 | async def read_item(item_id: str):
45 | return items[item_id]
46 |
47 |
48 | @app.get("/items/{item_id}/name", response_model=Item, response_model_include={"name", "description"})
49 | async def read_item_name(item_id: str):
50 | return items[item_id]
51 |
52 |
53 | @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={"tax"})
54 | async def read_item_public_data(item_id: str):
55 | return items[item_id]
56 |
--------------------------------------------------------------------------------
/drf/drf_minimal/README.md:
--------------------------------------------------------------------------------
1 | # DRF(Django REST framework) minimal
2 | Reference: [Django REST framework Quickstart](https://www.django-rest-framework.org/tutorial/quickstart/)
3 |
4 | ## Install
5 |
6 | ```shell
7 | $ python3 -m venv venv
8 | $ source ./venv/bin/activate
9 | $ pip install django==3.2.12
10 | $ pip install djangorestframework==3.12.4
11 | ```
12 | Set up a new project with a single application
13 | ```shell
14 | $ django-admin startproject project .
15 | $ django-admin startapp app
16 | $ cd ..
17 | ```
18 |
19 | ## Migration
20 | ```shell
21 | $ python manage.py migrate
22 | ```
23 |
24 | ## Create admin user
25 | Please input admin's password.
26 | ```shell
27 | $ python manage.py createsuperuser --email admin@taptorestart.com --username admin
28 | Password: verysecret
29 | Password (again): verysecret
30 | ```
31 |
32 | ## Run
33 | ```shell
34 | $ python manage.py runserver
35 | ```
36 |
37 | ## Screenshots
38 |
39 | 127.0.0.1:8000/
40 |
41 | 
42 |
43 | 127.0.0.1:8000/users/
44 |
45 | 
46 |
47 | Click login button! Input your username and password like 'admin' and 'verysecret'.
48 |
49 | 
50 |
51 | 127.0.0.1:8000/users/ admin
52 |
53 | 
54 |
55 | Post new user
56 |
57 | 
58 |
59 | Result
60 |
61 | 
62 |
63 | 127.0.0.1:8000/users/2/
64 |
65 | 
66 |
67 | 127.0.0.1:8000/users/1/
68 |
69 | 
70 |
--------------------------------------------------------------------------------
/event_streaming/kafka_python/README.md:
--------------------------------------------------------------------------------
1 | # kafka-python Example
2 | source: [https://github.com/dpkp/kafka-python](https://github.com/dpkp/kafka-python), Apache-2.0 License
3 |
4 | ## Kafka and MSA(Microservice Architecture)
5 | [How Kafka Solves Common Microservice Communication Issues](https://dzone.com/articles/how-kafka-solves-common-microservice-communication)
6 |
7 | ## Test Environments
8 | - Python v3.8.2
9 | - MacOS v12.2.1
10 |
11 | ## Install Kafka
12 | source: [Kafka Quick Start](https://kafka.apache.org/quickstart)
13 |
14 | ```shell
15 | # Download KAFKA
16 | [https://dlcdn.apache.org/kafka/3.1.0/kafka_2.13-3.1.0.tgz](https://dlcdn.apache.org/kafka/3.1.0/kafka_2.13-3.1.0.tgz)
17 |
18 | # STEP 1: GET KAFKA
19 | $ tar -xzf kafka_2.13-3.1.0.tgz
20 | $ cd kafka_2.13-3.1.0
21 |
22 | # STEP 2: START THE KAFKA ENVIRONMENT
23 | # Start the ZooKeeper service
24 | $ bin/zookeeper-server-start.sh config/zookeeper.properties
25 |
26 | # Start the Kafka broker service
27 | $ bin/kafka-server-start.sh config/server.properties
28 |
29 | # STEP 3: CREATE A TOPIC TO STORE YOUR EVENTS
30 | $ bin/kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092
31 |
32 | # STEP 4: WRITE SOME EVENTS INTO THE TOPIC
33 | $ bin/kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092
34 | This is my first event
35 | ```
36 |
37 | ## Install
38 | ```shell
39 | $ python3 -m venv venv
40 | $ sourcce ./venv/bin/activate
41 | $ pip install kafka-python==2.0.2
42 | ```
43 |
44 | ## Run
45 | Produce event
46 | ```shell
47 | $ python producer.py
48 | ```
49 |
50 | Consume event
51 | ```shell
52 | $ python consumer.py
53 | ```
54 |
55 | ## Screenshots
56 | 
57 |
--------------------------------------------------------------------------------
/drf/drf_swagger/README.md:
--------------------------------------------------------------------------------
1 | # DRF(Django REST framework) OpenAPI Specification(Swagger)
2 | Reference:
3 | - [Django REST framework Quickstart](https://www.django-rest-framework.org/tutorial/quickstart/)
4 | - [drf-yasg](https://drf-yasg.readthedocs.io/en/stable/)
5 |
6 | This example is using [DRF Minimal](https://github.com/taptorestart/python-backend-examples/tree/main/drf/drf_minimal).
7 |
8 |
9 | ## Install
10 | ```shell
11 | $ python3 -m venv venv
12 | $ source ./venv/bin/activate
13 | $ pip install -r requirements.txt
14 | ```
15 |
16 | ## Migration
17 | ```shell
18 | $ python manage.py migrate
19 | ```
20 |
21 | ## For swagger
22 | project/settings.py
23 | ```python
24 | INSTALLED_APPS = [
25 | ...
26 | 'drf_yasg',
27 | ]
28 | ```
29 |
30 | project/urls.py
31 | ```python
32 |
33 | # Swagger API
34 | schema_view = get_schema_view(
35 | openapi.Info(
36 | title="App API",
37 | default_version="v1",
38 | description="App API",
39 | ),
40 | public=True,
41 | permission_classes=(permissions.AllowAny,),
42 | )
43 |
44 | # swagger url
45 | urlpatterns += [
46 | re_path(r'^swagger(?P\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name="schema-json"),
47 | re_path(r'^swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
48 | re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
49 | ]
50 | ```
51 |
52 | ## Run
53 | ```shell
54 | $ python manage.py runserver
55 | ```
56 |
57 | Open your browser at '[http://127.0.0.1:8000/swagger](http://127.0.0.1:8000/swagger)'
58 |
59 | ## Screenshots
60 | You can see Open API documents.
61 |
62 | 
63 |
64 | 
65 |
66 | 
67 |
--------------------------------------------------------------------------------
/fastapi/fastapi_request_files/main.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from fastapi import FastAPI, File, UploadFile
4 | from fastapi.responses import HTMLResponse
5 | import shutil
6 |
7 | app = FastAPI()
8 |
9 |
10 | @app.post("/files/")
11 | async def create_files(
12 | files: List[bytes] = File(..., description="Multiple files as bytes")
13 | ):
14 | for index, file in enumerate(files):
15 | filename = f'{index}'
16 | save_bytes(file, '.', filename)
17 | return {"file_sizes": [len(file) for file in files]}
18 |
19 |
20 | def save_bytes(file_bytes: bytes, path: str, name: str):
21 | file = open(f'{path}/{name}', 'wb')
22 | try:
23 | file.write(file_bytes)
24 | finally:
25 | file.close()
26 |
27 |
28 | @app.post("/uploadfiles/")
29 | async def create_upload_files(
30 | files: List[UploadFile] = File(..., description="Multiple files as UploadFile")
31 | ):
32 | for file in files:
33 | save_upload_file(file, '.', file.filename)
34 | return {"filenames": [file.filename for file in files]}
35 |
36 |
37 | def save_upload_file(upload_file: UploadFile, path: str, name: str):
38 | with open(f'{path}/{name}', 'wb') as buffer:
39 | shutil.copyfileobj(upload_file.file, buffer)
40 |
41 |
42 | @app.get("/")
43 | async def main():
44 | content = """
45 |
46 | Multiple files as bytes
47 |
51 |
52 | Multiple files as UploadFile
53 |
57 |
58 |
59 | """
60 | return HTMLResponse(content=content)
61 |
--------------------------------------------------------------------------------
/flask/flask_file_upload/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template, request
2 | import os
3 | from werkzeug.utils import secure_filename
4 |
5 | app = Flask(__name__)
6 |
7 |
8 | @app.route('/')
9 | def index():
10 | return render_template("index.html")
11 |
12 |
13 | @app.route('/upload_test')
14 | def upload():
15 | return render_template("upload.html")
16 |
17 |
18 | @app.route('/upload_test_with_simple_button')
19 | def upload_test_with_simple_button():
20 | return render_template("upload_simple_button.html")
21 |
22 |
23 | # https://flask.palletsprojects.com/en/2.0.x/patterns/fileuploads/
24 | @app.route('/upload_test_with_secure_filename')
25 | def upload_test_with_secure_filename():
26 | return render_template("upload_test_with_secure_filename.html")
27 |
28 |
29 | @app.route('/upload', methods=['POST'])
30 | def post_upload_file():
31 | file = request.files['file']
32 | filename = file.filename
33 | path_to_save = "static/files"
34 | file.save(os.path.join(path_to_save, filename))
35 | filepath = "files/" + filename
36 | print(file.content_type)
37 | if 'image' in file.content_type:
38 | return render_template("uploaded_image.html", filepath=filepath)
39 | else:
40 | return filename
41 |
42 |
43 | @app.route('/upload_with_secure_filename', methods=['POST'])
44 | def upload_and_save_secure_filename():
45 | file = request.files['file']
46 | filename = secure_filename(file.filename)
47 | path_to_save = "static/files"
48 | file.save(os.path.join(path_to_save, filename))
49 | filepath = "files/" + filename
50 | print(file.content_type)
51 | if 'image' in file.content_type:
52 | return render_template("uploaded_image.html", filepath=filepath)
53 | else:
54 | return filename
55 |
56 |
57 | if __name__ == '__main__':
58 | app.run()
59 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_mysql/main.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from fastapi import Depends, FastAPI, HTTPException
4 | from sqlalchemy.orm import Session
5 |
6 | import crud
7 | import models
8 | import schemas
9 | from database import SessionLocal, engine
10 |
11 | models.Base.metadata.create_all(bind=engine)
12 |
13 | app = FastAPI()
14 |
15 |
16 | # Dependency
17 | def get_db():
18 | db = SessionLocal()
19 | try:
20 | yield db
21 | finally:
22 | db.close()
23 |
24 |
25 | @app.post("/users/", response_model=schemas.User)
26 | def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
27 | db_user = crud.get_user_by_email(db, email=user.email)
28 | if db_user:
29 | raise HTTPException(status_code=400, detail="Email already registered")
30 | return crud.create_user(db=db, user=user)
31 |
32 |
33 | @app.get("/users/", response_model=List[schemas.User])
34 | def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
35 | users = crud.get_users(db, skip=skip, limit=limit)
36 | return users
37 |
38 |
39 | @app.get("/users/{user_id}", response_model=schemas.User)
40 | def read_user(user_id: int, db: Session = Depends(get_db)):
41 | db_user = crud.get_user(db, user_id=user_id)
42 | if db_user is None:
43 | raise HTTPException(status_code=404, detail="User not found")
44 | return db_user
45 |
46 |
47 | @app.post("/users/{user_id}/items/", response_model=schemas.Item)
48 | def create_item_for_user(
49 | user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
50 | ):
51 | return crud.create_user_item(db=db, item=item, user_id=user_id)
52 |
53 |
54 | @app.get("/items/", response_model=List[schemas.Item])
55 | def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
56 | items = crud.get_items(db, skip=skip, limit=limit)
57 | return items
58 |
--------------------------------------------------------------------------------
/fastapi/fastapi_orm_sqlite/main.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from fastapi import Depends, FastAPI, HTTPException
4 | from sqlalchemy.orm import Session
5 |
6 | import crud
7 | import models
8 | import schemas
9 | from database import SessionLocal, engine
10 |
11 | models.Base.metadata.create_all(bind=engine)
12 |
13 | app = FastAPI()
14 |
15 |
16 | # Dependency
17 | def get_db():
18 | db = SessionLocal()
19 | try:
20 | yield db
21 | finally:
22 | db.close()
23 |
24 |
25 | @app.post("/users/", response_model=schemas.User)
26 | def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
27 | db_user = crud.get_user_by_email(db, email=user.email)
28 | if db_user:
29 | raise HTTPException(status_code=400, detail="Email already registered")
30 | return crud.create_user(db=db, user=user)
31 |
32 |
33 | @app.get("/users/", response_model=List[schemas.User])
34 | def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
35 | users = crud.get_users(db, skip=skip, limit=limit)
36 | return users
37 |
38 |
39 | @app.get("/users/{user_id}", response_model=schemas.User)
40 | def read_user(user_id: int, db: Session = Depends(get_db)):
41 | db_user = crud.get_user(db, user_id=user_id)
42 | if db_user is None:
43 | raise HTTPException(status_code=404, detail="User not found")
44 | return db_user
45 |
46 |
47 | @app.post("/users/{user_id}/items/", response_model=schemas.Item)
48 | def create_item_for_user(
49 | user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
50 | ):
51 | return crud.create_user_item(db=db, item=item, user_id=user_id)
52 |
53 |
54 | @app.get("/items/", response_model=List[schemas.Item])
55 | def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
56 | items = crud.get_items(db, skip=skip, limit=limit)
57 | return items
58 |
--------------------------------------------------------------------------------
/test/cors/README.md:
--------------------------------------------------------------------------------
1 | # CORS Test using Flask
2 |
3 | [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
4 |
5 | ## Environments
6 |
7 | - MacOS v13.2.1
8 | - Python v3.8.10
9 |
10 | ## Set hosts on Mac
11 | ```
12 | $ vi /etc/hosts
13 | ```
14 | Add your host like below:
15 |
16 | 127.0.0.1 localhost
17 | 127.0.0.1 local.taptorestart.com
18 |
19 | 
20 |
21 | ## Install
22 |
23 | ```
24 | $ python -m venv venv
25 | $ source ./venv/bin/activate
26 | $ pip install -r requirements.txt
27 | ```
28 |
29 | ## Install mkcert for https
30 | MacOS
31 | ```
32 | $ brew install mkcert
33 | $ brew install nss # for Firefox
34 | $ mkcert -install
35 | $ mkcert localhost
36 | or your site! ex: local.taptorestart.com
37 | $ mkcert local.taptorestart.com
38 | ```
39 |
40 | You can see results as shown below.
41 | ```
42 | % mkcert local.taptorestart.com
43 | Note: the local CA is not installed in the Firefox trust store.
44 | Run "mkcert -install" for certificates to be trusted automatically ⚠️
45 |
46 | Created a new certificate valid for the following names 📜
47 | - "local.taptorestart.com"
48 |
49 | The certificate is at "./local.taptorestart.com.pem" and the key at "./local.taptorestart.com-key.pem" ✅
50 |
51 | It will expire on 6 July 2025 🗓
52 | ```
53 |
54 | Now you can use https with pem files.
55 |
56 | ## Run
57 |
58 | Run app.py
59 | ```
60 | $ python app.py
61 | ```
62 |
63 | Run app_ssl.py
64 | ```
65 | $ python app_ssl.py
66 | ```
67 |
68 | Open your browser and test.
69 |
70 | ## Screenshots
71 |
72 | Test https://google.com. You can see a CORS error like below.
73 |
74 | from origin http://local.taptorestart.com:8000
75 |
76 | 
77 |
78 | from origin https://local.taptorestart.com:8000
79 |
80 | 
81 |
--------------------------------------------------------------------------------
/fastapi/fastapi_templates/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Templates
2 | source: [Fast API Tutorial - Templates](https://fastapi.tiangolo.com/advanced/templates/), MIT License
3 |
4 | FastAPI is using [starlette](https://www.starlette.io/). Read this documentation [Templates](https://www.starlette.io/templates/)
5 |
6 | Starlette is using Jinja2. Read the [jinja2 documentation](https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment)
7 |
8 | ## Test Environments
9 | Python v3.8.2
10 | MacOS v12.2.1
11 |
12 | ## Install
13 | ```shell
14 | $ mkdir fastapi_templates
15 | $ cd fastapi_templates
16 | $ python3 -m venv venv
17 | $ source ./venv/bin/activate
18 | $ pip install fastapi==0.75.0
19 | $ pip install "uvicorn[standard]"
20 | ```
21 |
22 | ## Run
23 | ```shell
24 | $ uvicorn main:app --reload
25 | ```
26 |
27 | ## Screenshots
28 |
29 | item.html
30 | ```html
31 |
32 |
33 | Item Details
34 |
35 |
36 |
37 |
38 |
39 | Item ID: {{ id }}
40 |
41 |
42 | ```
43 |
44 | 
45 |
46 | View source
47 | ```html
48 |
49 |
50 | Item Details
51 |
52 |
53 |
54 |
55 |
56 | Item ID: 3
57 |
58 |
59 | ```
60 |
61 | If you click "static/styles.css", you will show this message "{"detail":"Not Found"}"
62 |
63 | 
64 |
65 | If you click "/static/styles.css", you can see style.css.
66 | So you must set url with "/" like "/static/styles.css"!
67 |
68 | 
69 |
--------------------------------------------------------------------------------
/flask/flask_ajax/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Flask Ajax Example
6 |
7 |
9 |
12 |
13 |
24 |
25 |
26 |
27 |
Flask Ajax Example
28 |
34 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/depends.py:
--------------------------------------------------------------------------------
1 | import json
2 | from typing import Generator
3 |
4 | from fastapi import Depends, HTTPException, status
5 | from fastapi.security import OAuth2PasswordBearer
6 | from jose import jwt
7 | from pydantic import ValidationError
8 | from sqlalchemy.orm import Session
9 |
10 | from app.core.config import settings
11 | from app.db.session import SessionLocal
12 | from app.models.user import User
13 | from app.crud.user import crud_user
14 | from app.schemas.token import TokenPayload
15 |
16 | reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/login/access-token")
17 |
18 |
19 | def get_db() -> Generator:
20 | try:
21 | db = SessionLocal()
22 | yield db
23 | finally:
24 | db.close()
25 |
26 |
27 | def get_current_user(db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)) -> User:
28 | try:
29 | payload = jwt.decode(
30 | token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
31 | )
32 | token_data = TokenPayload(**payload)
33 | except (jwt.JWTError, ValidationError):
34 | raise HTTPException(
35 | status_code=status.HTTP_403_FORBIDDEN,
36 | detail="Could not validate credentials",
37 | )
38 | user = crud_user.get_by_email(db, email=token_data.sub)
39 | if not user:
40 | raise HTTPException(status_code=404, detail="User not found")
41 | return user
42 |
43 |
44 | def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
45 | if not crud_user.is_active(current_user):
46 | raise HTTPException(status_code=400, detail="Inactive user")
47 | return current_user
48 |
49 |
50 | def get_current_active_superuser(current_user: User = Depends(get_current_user)) -> User:
51 | if not crud_user.is_superuser(current_user):
52 | raise HTTPException(
53 | status_code=400, detail="The user doesn't have enough privileges"
54 | )
55 | return current_user
56 |
--------------------------------------------------------------------------------
/protocol/grpc_simple_message/user_pb2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by the protocol buffer compiler. DO NOT EDIT!
3 | # source: user.proto
4 | """Generated protocol buffer code."""
5 | from google.protobuf import descriptor as _descriptor
6 | from google.protobuf import descriptor_pool as _descriptor_pool
7 | from google.protobuf import message as _message
8 | from google.protobuf import reflection as _reflection
9 | from google.protobuf import symbol_database as _symbol_database
10 | # @@protoc_insertion_point(imports)
11 |
12 | _sym_db = _symbol_database.Default()
13 |
14 |
15 |
16 |
17 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\nuser.proto\x12\x04grpc\"J\n\x04User\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05\x65mail\x18\x02 \x01(\t\x12\x11\n\tis_active\x18\x03 \x01(\x05\x12\x14\n\x0cis_superuser\x18\x04 \x01(\x05\"\x1c\n\x0bUserRequest\x12\r\n\x05\x65mail\x18\x01 \x01(\t29\n\x0bUserService\x12*\n\x07GetUser\x12\x11.grpc.UserRequest\x1a\n.grpc.User\"\x00\x62\x06proto3')
18 |
19 |
20 |
21 | _USER = DESCRIPTOR.message_types_by_name['User']
22 | _USERREQUEST = DESCRIPTOR.message_types_by_name['UserRequest']
23 | User = _reflection.GeneratedProtocolMessageType('User', (_message.Message,), {
24 | 'DESCRIPTOR' : _USER,
25 | '__module__' : 'user_pb2'
26 | # @@protoc_insertion_point(class_scope:grpc.User)
27 | })
28 | _sym_db.RegisterMessage(User)
29 |
30 | UserRequest = _reflection.GeneratedProtocolMessageType('UserRequest', (_message.Message,), {
31 | 'DESCRIPTOR' : _USERREQUEST,
32 | '__module__' : 'user_pb2'
33 | # @@protoc_insertion_point(class_scope:grpc.UserRequest)
34 | })
35 | _sym_db.RegisterMessage(UserRequest)
36 |
37 | _USERSERVICE = DESCRIPTOR.services_by_name['UserService']
38 | if _descriptor._USE_C_DESCRIPTORS == False:
39 |
40 | DESCRIPTOR._options = None
41 | _USER._serialized_start=20
42 | _USER._serialized_end=94
43 | _USERREQUEST._serialized_start=96
44 | _USERREQUEST._serialized_end=124
45 | _USERSERVICE._serialized_start=126
46 | _USERSERVICE._serialized_end=183
47 | # @@protoc_insertion_point(module_scope)
48 |
--------------------------------------------------------------------------------
/flask/flask_orm/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, jsonify, request
2 | from flask_sqlalchemy import SQLAlchemy
3 | import os
4 |
5 |
6 | PROJECT_PATH = os.getenv('PROJECT_PATH')
7 | app = Flask(__name__)
8 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
9 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////{}/db.sqlite'.format(PROJECT_PATH)
10 | db = SQLAlchemy(app)
11 |
12 |
13 | # Model
14 | class Menu(db.Model):
15 | id = db.Column(db.Integer, primary_key=True, autoincrement=True)
16 | name = db.Column(db.String(32))
17 | price = db.Column(db.Integer)
18 |
19 |
20 | # Home
21 | @app.route('/')
22 | def index():
23 | return "Welcome in our restaurant!"
24 |
25 |
26 | # GET /menus
27 | @app.route('/menus', methods=['GET'])
28 | def get_menus():
29 | menus = []
30 | for m in Menu.query.all():
31 | menu = {}
32 | menu['id'] = m.id
33 | menu['name'] = m.name
34 | menu['price'] = m.price
35 | menus.append(menu)
36 | return jsonify({"menus": menus})
37 |
38 |
39 | # GET /menus/id
40 | @app.route('/menus/', methods=['GET'])
41 | def get_menus_by_id(menu_id):
42 | m = Menu.query.filter_by(id=menu_id).first()
43 | menu = {}
44 | menu['id'] = m.id
45 | menu['name'] = m.name
46 | menu['price'] = m.price
47 | return menu
48 |
49 |
50 | # POST /menus
51 | @app.route('/menus', methods=['POST'])
52 | def create_menus():
53 | req = request.get_json()
54 | print(req)
55 | menu = Menu(name=req['name'], price=req['price'])
56 | db.session.add(menu)
57 | db.session.commit()
58 | return jsonify(req), 201
59 |
60 |
61 | # PUT /menus
62 | @app.route('/menus/', methods=['PUT'])
63 | def update_menus(menu_id):
64 | req = request.get_json()
65 | Menu.query.filter_by(id=menu_id).update(dict(name=req['name'], price=req['price']))
66 | db.session.commit()
67 | return jsonify(req)
68 |
69 |
70 | # DELETE /menus
71 | @app.route('/menus/', methods=['DELETE'])
72 | def delete_menus(menu_id):
73 | Menu.query.filter_by(id=menu_id).delete()
74 | db.session.commit()
75 | return ''
76 |
--------------------------------------------------------------------------------
/django/django_pytest_with_bakery/README.md:
--------------------------------------------------------------------------------
1 | # Django bakery example
2 |
3 | ## Install
4 |
5 | Install django and make project and app.
6 |
7 | ```shell
8 | $ python3 -m venv venv
9 | $ source venv/bin/activate
10 | $ python -m pip install django==3.2.8
11 | $ python -m django startproject mysite .
12 | $ python manage.py startapp shop
13 | ```
14 |
15 | Install packages
16 | ```shell
17 | $ python -m pip install -r requirements.txt
18 | ```
19 |
20 | ## Add app on settings.py
21 | ```python
22 | INSTALLED_APPS = [
23 | ...,
24 | 'shop'
25 | ]
26 | ```
27 |
28 | ## Make model
29 | Source: https://github.com/model-bakers/model_bakery
30 |
31 | ```python
32 | # shop/models.py
33 | from django.db import models
34 |
35 |
36 | class Customer(models.Model):
37 | name = models.CharField(max_length=30)
38 | email = models.EmailField()
39 | age = models.IntegerField()
40 |
41 | ```
42 | Migrate
43 | ```shell
44 | $ python manage.py makemigrations
45 | $ python manage.py migrate
46 | ```
47 |
48 | ## pytest.ini
49 | ```
50 | [pytest]
51 | DJANGO_SETTINGS_MODULE = mysite.settings
52 | python_files = tests.py test_*.py *_tests.py
53 | addopts = -s
54 | ```
55 |
56 | ## Make test
57 | ```python
58 |
59 | import pytest
60 | from model_bakery import baker
61 | from shop.models import Customer
62 |
63 |
64 | @pytest.fixture
65 | def customer():
66 | """Fixture for baked Customer model."""
67 | return baker.make(Customer)
68 |
69 |
70 | @pytest.mark.django_db
71 | def test_using_customer(customer):
72 | """Test function using fixture of baked model."""
73 | print(customer.name)
74 | print(customer.email)
75 | print(customer.age)
76 | assert isinstance(customer, Customer)
77 |
78 | ```
79 |
80 | ## Run test
81 | ```shell
82 | $ pytest
83 | ```
84 |
85 | Results
86 | ```
87 | ....
88 | shop/test_models.py EfUFNbTbNVPozUsFnuLrzTQPHRnnGY
89 | QFPvQWyIhf@example.com
90 | -1218817325
91 | .
92 | ======= 1 passed in 0.20s =========
93 | ```
94 |
--------------------------------------------------------------------------------
/fastapi/fastapi_testing/test_main_extended.py:
--------------------------------------------------------------------------------
1 | from fastapi.testclient import TestClient
2 |
3 | from main_extended import app
4 |
5 | client = TestClient(app)
6 |
7 |
8 | def test_read_item():
9 | response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
10 | assert response.status_code == 200
11 | assert response.json() == {
12 | "id": "foo",
13 | "title": "Foo",
14 | "description": "There goes my hero",
15 | }
16 |
17 |
18 | def test_read_item_bad_token():
19 | response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
20 | assert response.status_code == 400
21 | assert response.json() == {"detail": "Invalid X-Token header"}
22 |
23 |
24 | def test_read_inexistent_item():
25 | response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
26 | assert response.status_code == 404
27 | assert response.json() == {"detail": "Item not found"}
28 |
29 |
30 | def test_create_item():
31 | response = client.post(
32 | "/items/",
33 | headers={"X-Token": "coneofsilence"},
34 | json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
35 | )
36 | assert response.status_code == 200
37 | assert response.json() == {
38 | "id": "foobar",
39 | "title": "Foo Bar",
40 | "description": "The Foo Barters",
41 | }
42 |
43 |
44 | def test_create_item_bad_token():
45 | response = client.post(
46 | "/items/",
47 | headers={"X-Token": "hailhydra"},
48 | json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
49 | )
50 | assert response.status_code == 400
51 | assert response.json() == {"detail": "Invalid X-Token header"}
52 |
53 |
54 | def test_create_existing_item():
55 | response = client.post(
56 | "/items/",
57 | headers={"X-Token": "coneofsilence"},
58 | json={
59 | "id": "foo",
60 | "title": "The Foo ID Stealers",
61 | "description": "There goes my stealer",
62 | },
63 | )
64 | assert response.status_code == 400
65 | assert response.json() == {"detail": "Item already exists"}
66 |
--------------------------------------------------------------------------------
/django/django_admin_register_app/README.md:
--------------------------------------------------------------------------------
1 | # Django Admin and Register app's model
2 | ## Reference
3 | - [Writing your first Django app, part 1](https://docs.djangoproject.com/en/3.2/intro/tutorial01/)
4 | - [Writing your first Django app, part 2](https://docs.djangoproject.com/en/3.2/intro/tutorial02/)
5 |
6 | ## Test Environments
7 | Python v3.8.2
8 | MacOS v12.2.1
9 | Django v3.2.12
10 |
11 | ## Install
12 | ```shell
13 | $ mkdir django_minimal
14 | $ cd django_minimal
15 | $ python3 -m venv venv
16 | $ source ./venv/bin/activate
17 | $ pip install django==3.2.12
18 | ```
19 |
20 | Set up a new project as config. Please don't forget write '.'.
21 | ```shell
22 | $ django-admin startproject config .
23 | ```
24 |
25 | Migrate
26 | ```shell
27 | $ python manage.py migrate
28 | ```
29 |
30 | Create a new app as cafe.
31 | ```shell
32 | $ python manage.py startapp cafe
33 | ```
34 |
35 | Please copy this project's files.
36 |
37 | Create migration files for cafe
38 | ```shell
39 | $ python manage.py makemigrations cafe
40 | ```
41 |
42 | Migrate for cafe
43 | ```shell
44 | $ python manage.py migrate
45 | ```
46 |
47 | ## Create an admin user
48 | ```shell
49 | $ python manage.py createsuperuser
50 | ```
51 | Please input admin user info like example below.
52 |
53 | - Username: admin
54 | - Email address: taptorestart@gmail.com
55 | - Password: verysecret
56 |
57 |
58 | ## Run
59 | ```shell
60 | $ python manage.py runserver
61 | ```
62 |
63 | Open your browser at 'http://127.0.0.1:8000/admin'
64 | 
65 |
66 | Login as admin
67 | 
68 |
69 | ## Add models to admin page
70 |
71 | ```python
72 | from django.contrib import admin
73 |
74 | from .models import Category, Beverage
75 |
76 | admin.site.register(Category)
77 | admin.site.register(Beverage)
78 | ```
79 |
80 | You can see the models on admin page.
81 | 
82 |
83 | You can add a object like below.
84 | 
85 |
86 | 
87 |
88 | 
89 |
90 | 
91 |
92 | 
93 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/crud/user.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Dict, Optional, Union
2 |
3 | from sqlalchemy.orm import Session
4 |
5 | from app.core.security import get_password_hash, verify_password
6 | from app.crud.base import CRUDBase
7 | from app.models.user import User
8 | from app.schemas.user import UserCreate, UserUpdate
9 |
10 |
11 | class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
12 | def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
13 | return db.query(User).filter(User.email == email).first()
14 |
15 | def create_superuser(self, db: Session, *, obj_in: UserCreate) -> User:
16 | db_obj = User(
17 | email=obj_in.email,
18 | password=get_password_hash(obj_in.password),
19 | is_superuser=obj_in.is_superuser
20 | )
21 | db.add(db_obj)
22 | db.commit()
23 | db.refresh(db_obj)
24 | return db_obj
25 |
26 | def create(self, db: Session, *, obj_in: UserCreate) -> User:
27 | db_obj = User(
28 | email=obj_in.email,
29 | password=get_password_hash(obj_in.password)
30 | )
31 | db.add(db_obj)
32 | db.commit()
33 | db.refresh(db_obj)
34 | del db_obj.password
35 | return db_obj
36 |
37 | def update(self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]) -> User:
38 | if isinstance(obj_in, dict):
39 | update_data = obj_in
40 | else:
41 | update_data = obj_in.dict(exclude_unset=True)
42 | if "password" in update_data:
43 | hashed_password = get_password_hash(update_data["password"])
44 | update_data["password"] = hashed_password
45 | return super().update(db, db_obj=db_obj, obj_in=update_data)
46 |
47 | def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
48 | user = self.get_by_email(db, email=email)
49 | if not user:
50 | return None
51 | if not verify_password(password, user.password):
52 | return None
53 | return user
54 |
55 | def is_active(self, user: User) -> bool:
56 | return user.is_active
57 |
58 | def is_superuser(self, user: User) -> bool:
59 | return user.is_superuser
60 |
61 |
62 | crud_user = CRUDUser(User)
63 |
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/crud/base.py:
--------------------------------------------------------------------------------
1 | from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
2 |
3 | from fastapi.encoders import jsonable_encoder
4 | from pydantic import BaseModel
5 | from sqlalchemy.orm import Session
6 |
7 | from app.db.session import Base
8 |
9 | ModelType = TypeVar("ModelType", bound=Base)
10 | CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
11 | UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
12 |
13 |
14 | class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
15 | def __init__(self, model: Type[ModelType]):
16 | """
17 | CRUD object with default methods to Create, Read, Update, Delete (CRUD).
18 |
19 | **Parameters**
20 |
21 | * `model`: A SQLAlchemy model class
22 | * `schema`: A Pydantic model (schema) class
23 | """
24 | self.model = model
25 |
26 | def get(self, db: Session, id: Any) -> Optional[ModelType]:
27 | return db.query(self.model).filter(self.model.id == id).first()
28 |
29 | def get_multi(
30 | self, db: Session, *, skip: int = 0, limit: int = 100
31 | ) -> List[ModelType]:
32 | return db.query(self.model).offset(skip).limit(limit).all()
33 |
34 | def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
35 | obj_in_data = jsonable_encoder(obj_in)
36 | db_obj = self.model(**obj_in_data) # type: ignore
37 | db.add(db_obj)
38 | db.commit()
39 | db.refresh(db_obj)
40 | return db_obj
41 |
42 | def update(
43 | self,
44 | db: Session,
45 | *,
46 | db_obj: ModelType,
47 | obj_in: Union[UpdateSchemaType, Dict[str, Any]]
48 | ) -> ModelType:
49 | obj_data = jsonable_encoder(db_obj)
50 | if isinstance(obj_in, dict):
51 | update_data = obj_in
52 | else:
53 | update_data = obj_in.dict(exclude_unset=True)
54 | for field in obj_data:
55 | if field in update_data:
56 | setattr(db_obj, field, update_data[field])
57 | db.add(db_obj)
58 | db.commit()
59 | db.refresh(db_obj)
60 | return db_obj
61 |
62 | def remove(self, db: Session, *, id: int) -> ModelType:
63 | obj = db.query(self.model).get(id)
64 | db.delete(obj)
65 | db.commit()
66 | return obj
67 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2/fastapi_oauth2.postman_collection.json:
--------------------------------------------------------------------------------
1 | {
2 | "info": {
3 | "_postman_id": "4cdfa5fb-ff6c-4c2b-add0-50205890c61c",
4 | "name": "fastapi_oauth2",
5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
6 | },
7 | "item": [
8 | {
9 | "name": "login",
10 | "request": {
11 | "method": "POST",
12 | "header": [],
13 | "body": {
14 | "mode": "formdata",
15 | "formdata": [
16 | {
17 | "key": "username",
18 | "value": "johndoe",
19 | "type": "text"
20 | },
21 | {
22 | "key": "password",
23 | "value": "secret",
24 | "type": "text"
25 | }
26 | ]
27 | },
28 | "url": {
29 | "raw": "http://127.0.0.1:8000/token",
30 | "protocol": "http",
31 | "host": [
32 | "127",
33 | "0",
34 | "0",
35 | "1"
36 | ],
37 | "port": "8000",
38 | "path": [
39 | "token"
40 | ]
41 | }
42 | },
43 | "response": []
44 | },
45 | {
46 | "name": "users/me",
47 | "request": {
48 | "auth": {
49 | "type": "bearer",
50 | "bearer": [
51 | {
52 | "key": "token",
53 | "value": "johndoe",
54 | "type": "string"
55 | }
56 | ]
57 | },
58 | "method": "GET",
59 | "header": [],
60 | "url": {
61 | "raw": "http://127.0.0.1:8000/users/me",
62 | "protocol": "http",
63 | "host": [
64 | "127",
65 | "0",
66 | "0",
67 | "1"
68 | ],
69 | "port": "8000",
70 | "path": [
71 | "users",
72 | "me"
73 | ]
74 | }
75 | },
76 | "response": []
77 | },
78 | {
79 | "name": "users/me with wrong token",
80 | "request": {
81 | "auth": {
82 | "type": "bearer",
83 | "bearer": [
84 | {
85 | "key": "token",
86 | "value": "test",
87 | "type": "string"
88 | }
89 | ]
90 | },
91 | "method": "GET",
92 | "header": [],
93 | "url": {
94 | "raw": "http://127.0.0.1:8000/users/me",
95 | "protocol": "http",
96 | "host": [
97 | "127",
98 | "0",
99 | "0",
100 | "1"
101 | ],
102 | "port": "8000",
103 | "path": [
104 | "users",
105 | "me"
106 | ]
107 | }
108 | },
109 | "response": []
110 | }
111 | ]
112 | }
--------------------------------------------------------------------------------
/fastapi/fastapi_email_login_jwt_mysql/app/api/api_v1/endpoints/users.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 |
3 | from fastapi import APIRouter, Depends, Body, HTTPException
4 | from fastapi.encoders import jsonable_encoder
5 | from pydantic.networks import EmailStr
6 |
7 | from app.api.depends import get_current_active_user, get_current_active_superuser
8 | from app.models.user import User
9 | from app.schemas.user import UserRead, UserUpdate
10 | from app.api.depends import get_db
11 | from sqlalchemy.orm import Session
12 | from app.crud.user import crud_user
13 |
14 | router = APIRouter()
15 |
16 |
17 | @router.get("/me", response_model=UserRead, response_model_exclude={"password"})
18 | def read_user_me(current_user: User = Depends(get_current_active_user)) -> UserRead:
19 | return current_user
20 |
21 |
22 | @router.patch('/me', response_model=UserRead, response_model_exclude={"password"})
23 | def update_user_me(*, db: Session = Depends(get_db), password: str = Body(None), email: EmailStr = Body(None), current_user: User = Depends(get_current_active_user)):
24 | current_user_data = jsonable_encoder(current_user)
25 | user_in = UserUpdate(**current_user_data)
26 | if password:
27 | user_in.password = password
28 | else:
29 | del user_in.password
30 | if email:
31 | user_has_same_email = crud_user.get_by_email(db=db, email=email)
32 | if user_has_same_email:
33 | raise HTTPException(status_code=400, detail="Email already registered")
34 | else:
35 | user_in.email = email
36 | user = crud_user.update(db, db_obj=current_user, obj_in=user_in)
37 | return user
38 |
39 |
40 | @router.get("/{user_id}", response_model=UserRead, response_model_exclude={"password"})
41 | def read_user_by_id(user_id: int, current_user: User = Depends(get_current_active_superuser), db: Session = Depends(get_db)) -> Any:
42 | user = crud_user.get(db, id=user_id)
43 | return user
44 |
45 |
46 | @router.patch("/{user_id}", response_model=UserRead, response_model_exclude={"password"})
47 | def update_user(*, user_id: int, user_in: UserUpdate, current_user: User = Depends(get_current_active_superuser), db: Session = Depends(get_db)) -> Any:
48 | user = crud_user.get(db, id=user_id)
49 | if not user:
50 | raise HTTPException(
51 | status_code=404,
52 | detail="The user with this user id does not exist in the system",
53 | )
54 | user = crud_user.update(db, db_obj=user, obj_in=user_in)
55 | return user
56 |
--------------------------------------------------------------------------------
/fastapi/fastapi_oauth2_jwt/fastapi_oauth2_jwt.postman_collection.json:
--------------------------------------------------------------------------------
1 | {
2 | "info": {
3 | "_postman_id": "2ef15a3a-0802-426d-8514-03d591f5d05e",
4 | "name": "fastapi_oauth2_jwt",
5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
6 | },
7 | "item": [
8 | {
9 | "name": "login",
10 | "request": {
11 | "method": "POST",
12 | "header": [],
13 | "body": {
14 | "mode": "formdata",
15 | "formdata": [
16 | {
17 | "key": "username",
18 | "value": "johndoe",
19 | "type": "text"
20 | },
21 | {
22 | "key": "password",
23 | "value": "secret",
24 | "type": "text"
25 | }
26 | ]
27 | },
28 | "url": {
29 | "raw": "http://127.0.0.1:8000/token",
30 | "protocol": "http",
31 | "host": [
32 | "127",
33 | "0",
34 | "0",
35 | "1"
36 | ],
37 | "port": "8000",
38 | "path": [
39 | "token"
40 | ]
41 | }
42 | },
43 | "response": []
44 | },
45 | {
46 | "name": "users/me",
47 | "request": {
48 | "auth": {
49 | "type": "bearer",
50 | "bearer": [
51 | {
52 | "key": "token",
53 | "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqb2huZG9lIiwiZXhwIjoxNjQ1NjczOTI2fQ.GnTLutzm2GQZAd7wJfR2pB3UF_4XKGP59bkOSHNQpmU",
54 | "type": "string"
55 | }
56 | ]
57 | },
58 | "method": "GET",
59 | "header": [],
60 | "url": {
61 | "raw": "http://127.0.0.1:8000/users/me",
62 | "protocol": "http",
63 | "host": [
64 | "127",
65 | "0",
66 | "0",
67 | "1"
68 | ],
69 | "port": "8000",
70 | "path": [
71 | "users",
72 | "me"
73 | ]
74 | }
75 | },
76 | "response": []
77 | },
78 | {
79 | "name": "users/me with wrong token",
80 | "request": {
81 | "auth": {
82 | "type": "bearer",
83 | "bearer": [
84 | {
85 | "key": "token",
86 | "value": "test",
87 | "type": "string"
88 | }
89 | ]
90 | },
91 | "method": "GET",
92 | "header": [],
93 | "url": {
94 | "raw": "http://127.0.0.1:8000/users/me",
95 | "protocol": "http",
96 | "host": [
97 | "127",
98 | "0",
99 | "0",
100 | "1"
101 | ],
102 | "port": "8000",
103 | "path": [
104 | "users",
105 | "me"
106 | ]
107 | }
108 | },
109 | "response": []
110 | }
111 | ]
112 | }
--------------------------------------------------------------------------------