Running Django on Android

Source: Internet
Author: User
Tags virtual environment

Here's an example of running Django on Android, where Django is usually run from the command line, and if you're running on Android, you'll need to load the Python interpreter from Java code, run the Django script, and change the Django startup parameters.

This example uses python2.7, first need to extract Django, install Diango in Windows, after the installation is complete, package catalog "\lib\site-ackages\django-1.10.5-py2.7.egg\django" For a zip, put it under the assets directory of the Android project, create the MySite site, pack the site into Mysite.zip, and put it under the assets directory of the Android project. 1. Create the project

This example code is developed using Eclipse and can be imported directly into Android studio.

To add a shared library file under the Libs directory:

Add a Python extension library under the assets directory, Django.zip and mysite.zip 2. Modify Django

Django loading requires a certain amount of time, after loading is complete, notify the interface, you need to set the shared variable mainactivity, the variable provides function ondjangoinitfinish, the function is written by Java, can be called by Python. Create an empty Python module file "starglobal.py" to manage Python variables

public void Ondjangoinitfinish ()
{message Message
    = Handler.obtainmessage ();
    message.what = 0;
    Message.obj = null;
    Handler.sendmessage (message);
}
Modify runserver.py, in django\ core\management\commands directory
def inner_run (self, *args, **options):
....
try:
    import starglobal
    starglobal. Mainactivity.ondjangoinitfinish ()  # notify host
    handler = Self.get_handler (*args, **options)
    run ( self.addr, Int (self.port), Handler,
        Ipv6=self.use_ipv6, threading=threading)

Modify the site's manage.py, and Django loads it into the loop, so in order to avoid blocking the interface thread, create a thread in Python to run. At the end of the manage.py run, into the CLE message loop, the interface creates a thread to initialize and load Django.
#!/usr/bin/env python import OS import sys import traceback import thread import Time Def doit (val): os.environ.setd Efault ("Django_settings_module", "mysite.settings") try:from django.core.management import Execute_from_comma Nd_line except Importerror: # The above import may fail to some other reason.
        Ensure that's # issue is really of that Django are missing to avoid masking and other # exceptions on Python 2. Try:import Django except ImportError:traceback.print_exc () raise IMP Orterror ("couldn ' t import Django.) Are you sure it's installed and "" available on your pythonpath?
        Did "" "Forget to activate a virtual environment?"
        Raise Execute_from_command_line ([' manage.py ', ' runserver ', '--noreload ']) if __name__ = "__main__": Try: Import Starglobal Starglobal. Mainactivity = Mainactivity Thread.start_new_thread (doit, (0,)) while True:while LIBSTARPY._SRPDISPATC H (False) = = True:pass Libstarpy._srpunlock () time.sleep (0.01) Libst
 Arpy._srplock () except Exception:traceback.print_exc ()
3. Initialize the Python interpreter and load the Django A. Copy python2.7.zip to "/data/data/" +getpackagename () + "/files" directory
        File Destdir = new file ("/data/data/" +getpackagename () + "/files");
        if (!destdir.exists ())
        	destdir.mkdirs ();        
        Java.io.File python2_7_libfile = new Java.io.File ("/data/data/" +getpackagename () + "/files/python2.7.zip");
        if (!python2_7_libfile.exists ()) {    
	        try{
	        	copyfile (This, "Python2.7.zip", null);
	        }
    	    catch (Exception e) {
        	}
        }  
B. Extract Django.zip and Mysite.zip to the "/data/data/" +getpackagename () + "/files" directory
        try{
        	Assetmanager Assetmanager = Getassets ();
        	InputStream DataSource = Assetmanager.open ("Django.zip");
        	Unzip (DataSource, "/data/data/" +getpackagename () + "/files", false);
        	Datasource.close ();
        	DataSource = Assetmanager.open ("Mysite.zip");
        	Unzip (DataSource, "/data/data/" +getpackagename () + "/files", false);
        catch (Exception e)
        {
        	
        }
c. Copy the Python extensions that Django needs to load into the "/data/data/" +getpackagename () + "/files" directory
try{CopyFile (This, "zlib.so", null);
        	CopyFile (This, "_json.so", null);
        	CopyFile (This, "_random.so", null);
        	CopyFile (This, "_socket.so", null);
        	CopyFile (This, "_sqlite3.so", null);
        	CopyFile (This, "select.so", null);
        	CopyFile (This, "time.so", null);
        	CopyFile (This, "unicodedata.so", null);
        	CopyFile (This, "datetime.so", null);
        	CopyFile (This, "fcntl.so", null);
        	CopyFile (This, "_struct.so", null);
        	CopyFile (This, "binascii.so", null);
        	CopyFile (This, "_collections.so", null);
        	CopyFile (This, "operator.so", null);
        	CopyFile (This, "itertools.so", null);
        	CopyFile (This, "_functools.so", null);
        	CopyFile (This, "math.so", null);
        	CopyFile (This, "_io.so", null);
        	CopyFile (This, "cstringio.so", null);
        	CopyFile (This, "_hashlib.so", null);
        	CopyFile (This, "array.so", null);
        CopyFile (This, "cpickle.so", null);
     catch (Exception e) {   	System.out.println (e);
 }

D. Initialize the CLE and Python interpreter, set the module search path, load the manage.py
        /*----INIT starcore----*/Starcorefactorypath.starcorecorelibrarypath = This.getapplicationinfo (). Nativeli
        Brarydir;
        Starcorefactorypath.starcoresharelibrarypath = This.getapplicationinfo (). Nativelibrarydir;
        
        Starcorefactorypath.starcoreoperationpath = "/data/data/" +getpackagename () + "/files";
        Final String libpath = This.getapplicationinfo (). Nativelibrarydir;
        Final activity gactivity = this; New Thread (New Runnable () {@Override public void run () {starcorefactory starcore= Starc
		        Orefactory.getfactory ();
		        Starserviceclass service=starcore._initsimple ("Test", "123", 0,0);
		        Starsrvgroupclass Srvgroup = (starsrvgroupclass) service._get ("_servicegroup");
		        
		        Service._checkpassword (FALSE);
		        /*----Run Python code----/* SRVGROUP._INITRAW ("python", Service);
		       Starobjectclass python = service._importrawcontext ("Python", "", False, ""); Python._call ("Import", "SYS");
		        Starobjectclass Pythonsys = python._getobject ("sys");
		        Starobjectclass Pythonpath = (starobjectclass) pythonsys._get ("path");
		        Pythonpath._call ("Insert", 0, "/data/data/" +getpackagename () + "/files/python2.7.zip");
		        Pythonpath._call ("Insert", 0,libpath);
		        Pythonpath._call ("Insert", 0, "/data/data/" +getpackagename () + "/files");		
		        Pythonpath._call ("Insert", 0, "/data/data/" +getpackagename () + "/files/django");
		
		        Pythonpath._call ("Insert", 0, "/data/data/" +getpackagename () + "/files/mysite");
		 	
		        Python._set ("Mainactivity", gactivity); 
            Service._dofile ("Python", "/data/data/" +getpackagename () + "/files/mysite/manage.py", "");
 }). Start ();
4. Operating results and instance downloads
You can also place Django and MySite on the SD card, and the search path for the module needs to be modified to download the sample




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.