Skip to content

Instantly share code, notes, and snippets.

@xiaket

xiaket/init_django.py

Last active May 21, 2020
Embed
What would you like to do?
Setup Django environment in Pythonista 3 on iOS. Works with Django 2.0+, must have stash installed.
#!/usr/bin/env python
import io
import os
import tarfile
import requests
import stash
SITE_PACKAGES = os.path.expanduser("~/Documents/site-packages-3")
ICLOUD = (
'/private/var/mobile/Library/Mobile Documents/'
'iCloud~com~omz-software~Pythonista3/Documents/'
)
MANAGE_PY = """{imports}
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
def run(args):
os.environ["DJANGO_SETTINGS_MODULE"] = "{name}.settings"
from django.core.management import execute_from_command_line as execute
execute(['manage.py'] + args)
{mains}"""
HELPER_PY = """#!/usr/bin/env python3
import os
from manage import run
run(os.path.split(__file__)[-1][:-len(".py")].split("_"))
"""
HELPERS = [
"runserver --noreload",
"migrate",
]
def install_django():
try:
import django
return
except ImportError:
pass
print("Installing Django")
url = "https://pypi.python.org/pypi/django/json"
response = requests.get(url).json()
download_url = [
url_dict["url"]
for url_dict in response["urls"]
if url_dict["packagetype"] == "sdist"
][0]
response = requests.get(download_url)
fobj = io.BytesIO(response.content)
tar = tarfile.open(fileobj=fobj)
package_name = download_url.split("/")[-1][: -len(".tar.gz")]
def members(tar):
for member in tar.getmembers():
if member.path.startswith(f"{package_name}/django/"):
member.path = member.path[len(f"{package_name}/") :]
yield member
tar.extractall(path=SITE_PACKAGES, members=members(tar))
def init_project():
name = input("Please enter project name: ").lower()
project_root = f"{ICLOUD}/{name.upper()}"
os.mkdir(project_root)
_stash = stash.core.StaSh(
no_cfgfile=True, no_rcfile=True, no_historyfile=True, command=False,
)
_stash.launch()
command = (
f"{SITE_PACKAGES}/django/bin/django-admin.py "
f"startproject {name} '{project_root}'"
)
_stash(command, add_to_history=False, persistent_level=0)
return name
def patch_project(name):
project_root = f"{ICLOUD}/{name.upper()}"
with open(f"{project_root}/manage.py") as fobj:
lines = fobj.readlines()
sep = [i for i, line in enumerate(lines) if line.strip() == ""][0]
with open(f"{project_root}/manage.py", 'w') as fobj:
fobj.write(
MANAGE_PY.format(
imports="".join(lines[:sep]), mains="".join(lines[sep:]),
name=name,
)
)
for helper in HELPERS:
with open(f"{project_root}/{helper.replace(' ', '_')}.py", 'w') as fobj:
fobj.write(HELPER_PY.format(name=name))
def main():
install_django()
project_name = init_project()
patch_project(project_name)
print("To finalize the process, please quit Pythonista 3 now.")
if __name__ == "__main__":
main()
@codecowboy

This comment has been minimized.

Copy link

@codecowboy codecowboy commented May 21, 2020

Hi,

This just creates an empty folder for me - no project structure or manage.py. Would be grateful for some assistance. Perhaps over at https://join.slack.com/t/pythonista-app/shared_invite/zt-e0lqpqxf-KeycxIw~tLZ1gS3485rgXg ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.