Django

Django

Explore django code snippets and tutorials

Django

Async view example with django

async view example with django

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from asgiref.sync import sync_to_async
from django.shortcuts import render


def _get_data(name):
    data = []
    for i in range(0,100000):
        data.append(f'{i} - {name}')
    return data

get_data = sync_to_async(_get_data, thread_sensitive=True)


async def home(request):
    context = {}
    data = get_data('hello word')
    context['data'] = await data
    return render(request,'home.html', context)
Django

django raw sql query as dict

django raw sql query as dict

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# it is copy paste from the django documentation 
# the difference is in this function is that  an sql string is passed as parameter instead of cursor

from django.db import connection

def dictfetchall(query):
    "Return data from raw sql query  as a dict"
    with connection.cursor() as cursor:
        cursor.execute(query)
        columns = [col[0] for col in cursor.description]
        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]
Django

Save django images programmatically

Save django images programmatically

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import requests
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand, CommandError
from app.models import MyModel


class Command(BaseCommand):
    help = 'save images to MyModel table'


    def handle(self, *args, **options):
        for model in MyModel.objects.all():
            url = 'url_path_to_image'
            r = requests.get(url)
            if r.status_code == 200:
                data = r.content
                filename = url.split('/')[-1]
                model.image.save(filename, ContentFile(data))
                model.save()
                print(model.pk)
        self.stdout.write(self.style.SUCCESS('Successfully saved MyModel images'))
Django

fabric2 commands for django development

fabric version 2 commands for django development

python
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from fabric import task
from pathlib import Path
import os
from fabric import Connection
from os.path import expanduser
from fabric import Connection, Config
home = expanduser("~")

SUDO_PASS = ''
user = ''
sudo_user = ''
server_ip = ''
project = 'projectname'
repo_dir = '/path/to/projectname'
venv_dir = 'path/to/project/name'
ssh_path = os.path.join(home, '.ssh', 'file.pub')
print(ssh_path)

config = Config(overrides={'sudo': {'password': SUDO_PASS, 'sudo_user': sudo_user}})

# Commands
@task
def updatedeps(c):
    """
    Installs the packages listed in "requirements.txt" in the virtualenv.
    """
    c.run(f'source {venv_dir}/activate && cd {repo_dir} && pip install --upgrade -r requirements.txt')

@task
def cleanpyc(c):
    c.run(f'source {venv_dir}/activate && cd {repo_dir}/{project} && find . -type f -name "*.pyc" -delete')


@task
def update(c):
    """
    Updates the code from the remote repository.
    """
    c.run(f'source {venv_dir}/activate && cd {repo_dir} && git stash && git pull --ff-only origin master && git status')


@task
def listcommands(c):
    """
    Lists all available management commands.
    """
    c.run(f' source {venv_dir}/activate && cd {repo_dir}/{project} && python manage.py')



@task
def runcommand(c, cmd):
    """
    Runs a management command.
    Use like:
        $ fab runcommand:'test -v 3 myapp'
    """
    c.run(f'source {venv_dir}/activate && cd {repo_dir}/{project} && python manage.py {cmd}')


@task
def collectstatic(c):
    """
    Runs "./manage.py collectstatic"
    """
    c.run(f'source {venv_dir}/activate;cd {repo_dir}/{project} && python manage.py collectstatic --noinput -v 1')


@task
def compress(c):
    """
    Runs "./manage.py collectstatic"
    """
    c.run(f'source {venv_dir}/activate;cd {repo_dir}/{project} && python manage.py compress --force')


@task
def loadfixture(c, fixture):
    """
    Installs the given fixture.
    """
    c.run(f'source {venv_dir}/activate;cd {repo_dir}/{project} && python manage.py loaddata {fixture}')

@task
def migrate(c):
    """
    Runs "./manage.py migrate"
    """
    c.run(f'source {venv_dir}/activate;cd {repo_dir}/{project} && python manage.py migrate')

@task
def restart_uwsgi(c):
    """
    Restart the frontend and backend sites for uwsgi emperor.
    """
    c.run(f'cd {repo_dir}/deploy && touch uwsgi.ini')


@task
def restart_supervisor(c):
    """
    Restart the frontend and backend sites for uwsgi emperor.
    """
    c.sudo('supervisorctl reread')
    c.sudo('supervisorctl update')
    c.sudo('supervisorctl status')


@task
def deploy(c):
    """
    Updates the code and restarts the frontend and backend sites.
    """
    c = Connection(
        host=server_ip,
        user=user,
        connect_kwargs={
            "key_filename": ssh_path,
        },
        config=config
    )
    update(c)
    collectstatic(c)
    #compress()
    runcommand(c, 'clear_cache')
    # runcommand(c, 'thumbnail cleanup')
    # runcommand(c, 'thumbnail clear')
    # runcommand(c, 'thumbnail clear_delete_referenced')
    # runcommand(c, 'thumbnail clear_delete_all')
    runcommand(c, 'ping_google "/sitemap.xml"')
    runcommand(c, 'ping_google "/sitemap-category.xml"')
    runcommand(c, 'ping_google "/sitemap-location.xml"')
    runcommand(c, 'ping_google "/sitemap-location1.xml"')
    runcommand(c, 'ping_google "/sitemap-poi1.xml"')
    runcommand(c, 'ping_google "/sitemap-poi2.xml"')
    runcommand(c, 'ping_google "/sitemap-poi.xml"')


    # migrate()
    # cleanpyc()
    # updatedeps()
    restart_supervisor(c)