[PYTHON] How to use Azure Table storage from Django (PTVS)

What is Table storage?

Azure Table Storage Service (https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-table-storage/) stores a large amount of structured data. I will. This service is a ** NoSQL datastore ** that accepts authenticated calls from inside and outside the Azure cloud. The point is that you can store SQL data externally. Using PTVS This is useful when you want to use SQL with Django.

Django application creation

We will create it by referring to the site of here. First, create a new Django app. Please refer to here for the creation method. Please download the ** azure ** package with pip using ** Install Python Package **. azure_pip.png

Storage creation

At the Azure Portal (https://portal.azure.com/) Select ** [Storage Account] ➡︎ [Add] **. Basically, you can decide only the ** name ** part and then use the default settings. Also, if you have not created a ** resource group **, create one! ストレージ設定.png

Once created, the storage account will be from the account you just created ** [Account] ➡︎ [Access key] ➡︎ [Storage account / key] ** Let's remember! Required when accessing from the outside. アクセスキー.png

Fill in the source code

I referred from the site introduced first. I will omit the explanation of imported azure, but if you want to know more, [here](https://github.com/yuesan/azure-content-jajp/blob/master/articles/storage/storage-python-how- There is an explanation in to-use-table-storage.md).

views.py


from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime

from django.http import HttpResponse
from django.template.loader import render_to_string
from azure.storage.table import TableService, Entity

account_name = 'Storage account name'
account_key = 'key(Any of multiple keys is fine)'
table_service = TableService(account_name=account_name, account_key=account_key)
table_service.create_table('mytasks')

def list_tasks(request):      
    entities = table_service.query_entities('mytasks', '', 'name,category')
    html = render_to_string('app/test.html', {'entities':entities})     
    return HttpResponse(html)
 
 
def add_task(request):     
    name = request.GET['name']     
    category = request.GET['category']       
    table_service.insert_entity('mytasks', {'PartitionKey':name+category, 'RowKey':name, 'name':name, 'category':category})     
    entities = table_service.query_entities('mytasks', '', 'name,category')     
    html = render_to_string('app/test.html', {'entities':entities})     
    return HttpResponse(html)
 
def update_task(request):     
    name = request.GET['name']     
    category = request.GET['category']        
    partition_key = name + category     
    row_key = name     
    table_service.update_entity('mytasks', partition_key, row_key, {'PartitionKey':partition_key, 'RowKey':row_key, 'name': name, 'category':category})     
    entities = table_service.query_entities('mytasks', '', 'name,category')         
    html = render_to_string('app/test.html', {'entities':entities})     
    return HttpResponse(html)

test.html


<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>     
    <body>
        <h2>My Tasks</h2> <br>     
        <table border="1">
            <tr>
                <td>Name</td>
                <td>Category</td>
            </tr>     
            {% for entity in entities %}     
                <form action="update_task" method="GET">
                    <tr>
                        <td>{{entity.name}} <input type="hidden" name='name' value="{{entity.name}}"></td>     
                        <td>{{entity.category}} 
                            <input type="hidden" name='category' value="{{entity.category}}"></td>     
                    </tr>     
                </form>     
            {% endfor %}     
        </table>     
        <br>     
        <hr>    
        <table border="1">
            <form action="add_task" method="GET">
                <tr>
                    <td>Name:</td
                    ><td><input type="text" name="name"></input></td>
                </tr>     
                <tr>
                    <td>Category:</td>
                    <td><input type="text" name="category"></input></td>
                </tr>     
                <tr>
                    <td><input type="submit" value="add task"></input></td>
                </tr>     
            </form>     
        </table>     
    </body>     
</html>

urls.py


urlpatterns = [
    url(r'^$', 'app.views.list_tasks'),
    url(r'^list_tasks$', 'app.views.list_tasks'),
    url(r'^add_task$', 'app.views.add_task'),
    url(r'^update_task$', 'app.views.update_task')

Run

When you execute it, there are ** Name: ** and ** Category **, so fill in each and add task will store the value in ** My Tasks **. You can also re-fill it or restart Django, of course, but the values will be preserved.

起動1.png 起動2.png

At the end

You can see that the value is actually inserted from the storage account. It's very difficult and annoying to actually install SQL in Windows, so I think it's a very nice feature, so please give it a try.

Recommended Posts

How to use Azure Table storage from Django (PTVS)
How to use SWIG from waf
Use Azure Blob Storage from Python
[TF] How to use Tensorboard from Keras
Create and deploy a Django (PTVS) app using Azure Table storage
Study from Python Hour7: How to use classes
Azure External Storage MySQL Challenges with Django (PTVS)
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
[BigQuery] How to use BigQuery API for Python -Table creation-
[Python] [Django] How to use ChoiceField and how to add options
How to use Keras ~ From simple model generation to CNN ~
How to use bootstrap in Django generic class view
How to use Django on Google App Engine / Python
How to use Decorator in Django and how to make it
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio