BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Hello World - on Shared Host

django.png




Bookmark and Share





bogotobogo.com site search:




Hello World on Shared Host

In the previous chapters, we've learned how to setup "Hello World" example on a local host.

In this chapter, we'll do it on a shared host environment.

"Although WSGI is the preferred deployment platform for Django, many people use shared hosting, on which protocols such as FastCGI, SCGI or AJP are the only viable options." - from How to use Django with FastCGI, SCGI, or AJP

Another reference: Using Django with FastCGI.



HelloWorldSharedHost.png



Install Python 2.7.2
$ mkdir ~/python
$ cd ~/python
$ wget http://www.python.org/ftp/python/2.7.2/Python-2.7.2.tgz
$ tar zxfv Python-2.7.2.tgz
$ rm -rf Python-2.7.2.tgz
$ find ~/python -type d | xargs chmod 0755
$ cd Python-2.7.2
$ ./configure --prefix=$HOME/python
$ make
$ make install
$ cd ..
$ rm -rf Python-2.7.2




~/.bashrc

Add the following lines of code to ~/.bashrc and do source it:

export PATH=$HOME/python/bin:$PATH 
source ~/.bashrc




Install setuptools
$ wget http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz
$ tar xzvf setuptools-0.6c11.tar.gz
$ rm setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11
$ python setup.py install
$ cd ..
$ rm -rf setuptools-0.6c11




Install pip
$ wget http://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
$ tar xzvf pip-1.2.1.tar.gz
$ rm pip-1.2.1.tar.gz
$ cd pip-1.2.1
$ python setup.py install
$ cd ..
$ rm -rf pip-1.2.1




Install Django, flup and MySQL Python Module
$ pip install Django
$ pip install flup
$ pip install MySQL-python




Where is Django?

We can find where the Django has been installed:

$ python
Python 2.7.2 (default, Jun 11 2014, 13:22:49) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux3
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django
<module 'django' from '/home2/bogotob1/python/lib/python2.7/site-packages/django/__init__.pyc'>




Configure our site
$ mkdir ~/djangoproject
$ cd ~/djangoproject
$ django-admin.py startproject djangoproject
$ cd ~/public_html/djangoproject

Note that the name (djangoproject) itself doesn't matter. We can use any name.

Then, we need to create a simple FCGI program under our ~/public_html/djangoproject/ directory. It will be executed that will dispatch web requests to our Django site. So, let's make djangoproject.fcgi file.

#!/home/your_username/python/bin/python
import sys, os
sys.path.insert(0, "/home/username/python")
sys.path.insert(13, "/home/username/djangoproject")
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproject.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

Change the file permission:

$ chmod 0755 djangoproject.fcgi




Create a Django Application

Let's make a Django Application (djangoapp):

$ python manage.py startapp djangoapp

tree.png




.htaccess

We need to create .htaccess file under the root directory of our Django project which is ~/public_html/djangoproject:

$ cd ~/public_html/djangoproject

Add the following to .htaccess:

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]




djangoproject.fcgi

~/public_html/djangoproject/djangoproject.fcgi file should look like this:

#!/home/directory/bin/python
import sys, os

sys.path.insert(0, "/home/directory/python")
sys.path.insert(13, "/home/directory/djangoproject")

os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproject.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")




urls.py
# djangoproject/urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'djangoapp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)




views.py
# djangoapp/views.py

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello World")




result

As shown in the introduction, we get this on our browser:


HelloWorldSharedHost.png



Document root directory

Until this section, we set the root directory as ~/public_html/djangoproject. However, we can switch it to any directory, for example, we can use ~/public_html/dj by putting the following two files into the root folder: ~/public_html/dj/djangoproject.fcgi and ~/public_html/dj/.htaccess. The contents of the files remain the same:

~/public_html/dj/djangoproject.fcgi:

#! /home2/bogotob1/python/bin/python
import sys, os
sys.path.insert(0, "/home2/bogotob1/python")
sys.path.insert(13, "/home2/bogotob1/djangoproject")
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproject.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

~/public_html/dj/.htaccess:

# django
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ djangoproject.fcgi/$1 [QSA,L]

The urls of the two pictures below are defined in ~/djangoproject/djangoproject/urls.py (remains the same, not modified):

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'djangoapp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)

HelloWorldSharedHostDJ.png

SharedHostHelloWorldAdmin.png



Home view - dynamic contents

We can make the home view dynamic by modifying the ~/djangoproject/djangoapp/views.py:

from django.http import HttpResponse

def home(request):
    name = "Bogotobogo Django"
    html = "<html><body>Hello %s </body></html>" % name
    return HttpResponse(html)

The third line of home() within the view constructs an HTML response using Python's "format-string" capability. The %s within the string is a placeholder, and the percent sign after the string means "Replace the %s in the preceding string with the value of the variable name." This will result in an HTML string such as "Hello Bogotobogo Django.". Finally, the view returns an HttpResponse object that contains the generated response


viewChange.png



Home view using template
$ cd djangoapp
$ mkdir -p templates/helloDJ
$ touch templates/helloDJ/base.html

basehtml.png

The base.html looks like this:

<html>
  <head>
    <title>This is Hello World app!</title>
  </head>
  <body>
    <h1>Welcome to Django at bogotobogo.com</h1>
    {% block content %}
    {% endblock %} 
  </body>
</html>

Everything is a normal html except for the {% block %} part. Djangle template language provides us dynamic contents and something will happen in the block portion. Actually, Django equips us for tags, filters, and output.

We may want to create another template called home.html:

{% extends "helloDJ/base.html" %}
{% block content %}
{{ Testing }}
{{ HelloHello }}
{% endblock %}

This demonstrates the inheritance of the template. The extends block tag means home.html will be shown inside base.html. The two braces "{{" and "}}" are basically a print statement.

Our base.html will stay with little change throughout several html pages. But the extension will take any specifics of a certain page within the frame of the base.html. In other words, any block in home.html will show up in the same named block in base.html

.

base_home_html.png

The {{ HelloHello }} will output the variable HelloHello passed by the views. So, we need to go back and fix our views.py. With the following views.py:

from django.shortcuts import render_to_response

def home(request):

   return  render_to_response("helloDJ/home.html",
                    {"Testing" : "Django Template Inheritance ",
                    "HelloHello" : "Hello World - Django"})

we get the the page shown below:


template_view.png

Note that the HelloHello is a variable and it's a key for dictionary feed for the template. Django will take over and properly render a page for us.





HttpResponse vs HttpResponseRedirect vs render_to_response

From stackoverflow.

  1. response = HttpResponse("Text of a web page.")
    This will create a new HttpResponse object with HTTP code 200 (OK), and the content passed to the constructor. In General, we should only use this for really small responses (like an AJAX form return value, if its really simple - just a number or so).
  2. HttpResponseRedirect("http://example.com/")
    This will create a new HttpResponse object with HTTP code 302 (Found/Moved temporarily). This should be used only to redirect to another page (e.g. after successful form POST)
    class HttpResponseRedirect : The constructor takes a single argument -- the path to redirect to. This can be a fully qualified URL (e.g. 'http://www.yahoo.com/search/') or an absolute URL with no domain (e.g. '/search/'). Note that this returns an HTTP status code 302.
  3. render_to_response(template[, dictionary][, context_instance][, mimetype]) :
    This renders a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
    This is a call to render a template with given dictionary of variables to create the response for us. This is what we should be using most of the time, because we want to keep our presentation logic in templates and not in code.












Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master