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

3. Hello World - urls & views

django.png




Bookmark and Share





bogotobogo.com site search:




Note

Everybody starts with Hello World. I was not an exception, either. It takes time to learn something, especially, it's not a primary everyday task at work place.

Django was my side kick and it took me several years to get used to it. Still, I consider myself as a novice.

It's been very hard to set aside a time slot for Django. But I managed to start something real such as this:


einsteinish-com.png

I've been exposed to couple of web frameworks, and currently managing my sites with RubyOnRails, Angular/Node, Laravel, and Django. I prefer Django over others. Probably, not just because I like Python but also Python has several promising areas including NLTK/Scikit/Spark and also graphics tool like Matplotlib which seems to be overcoming once the hot one like D3.js.

So, if you're new to Django, I encourage you to move forward and learn it.

If you're new to REST, then you can try lighter ones such as Bottle or Flask (actually, I haven't tried Flask).





Hello World Project

In the previous chapters, we've learned how to setup project and made a polling app utilizing SQL. However, it's a little bit tougher than this "Hello World" example that I'll show in this chapter. So, let's pause the polling app here, instead do a simpler one first. We'll resume the polling project in later chapters.

In this chapter, we'll take much simpler project as a review what we've learned so far.

Let's create a HelloWorld project:

$ django-admin.py startproject HelloWorld
$ cd HelloWorld
$ ls
HelloWorld  manage.py

HelloWorld_TreeA.png

Note that we have manage.py file and HelloWorld folder inside HelloWorld project.

  1. __init__.py: An empty file that tells Python that this directory should be considered a Python package.
  2. settings.py: Settings/configuration for this Django project. Django settings will tell us all about how settings work. In other words, this file will hold all apps, database settings information.
  3. urls.py: The url declarations for this Django project; a "table of contents" of our Django-powered site. This is a file to hold the urls of our website such as "http://localhost/HelloWorldApp". In order to use /HelloWorldApp in our HelloWorld project we have to mention this in urls.py.
  4. wsgi.py: An entry-point for WSGI-compatible web servers to serve our project. This file handles our requests/responses to/from django development server.




Running a development server

Inside the HelloWorld project directory, we need to run the development server:

$ python manage.py runserver
Validating models...

0 errors found
...
Django version 1.6.5, using settings 'HelloWorld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Open a browser and put "http://127.0.0.1:8000/" into url box, then we get the default page:


BrowserDjango.png



Creating Hello World App

To create an app (inside HelloWorld project directory), we need to run the following command:

$ django-admin startapp HelloWorldApp
$ ls
HelloWorld  HelloWorldApp  manage.py

HelloWorldAppTree.png

As we can see from the layout in picture above, the django-admin startapp app created files:

  1. __init__.py - this file indicates our app as python package.
  2. models.py - file to hold our database informations.
  3. views.py - our functions to hold requests and logics.
  4. tests.py - for testing.




Edit settings.py

We need to edit settings.py under HelloWorld project directory to add our application HelloWorldApp as shown below:

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HelloWorldApp',
)




Edit urls.py

How does Django know what view to send a particular request?
Django uses a mapping file called urls.py which maps html addresses to views, using regular expressions. In other words, Django has a way to map a requested url to a view which is needed for a response via regular expressions.

Let's modify the urls.py which is under the project directory, HelloWorld:

from django.conf.urls import patterns, include, url
from HelloWorldApp.views import foo

#from django.contrib import admin
#admin.autodiscover()

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

    #url(r'^admin/', include(admin.site.urls)),
    url(r'HelloWorldApp/$', foo),
)

In the commented lines, we have ^$. Since the caret(^) means the start and the dollar($) means the end, ^$ indicates we got nothing. The r in "url(r..) is not a part of regex but it's a python indicating "raw" to prevent any character in regex from being parsed in python's way. In other words, it tells python that a string is "raw" - that nothing in the string should be escaped.

The url() is a function call that builds url patterns and it takes five arguments, most of which are optional:

url(regex, view, kwargs=None, name=None, prefix='')

The foo is the Python import string to get to a view.

Visit django.conf.urls utility functions for more information.





Edit views.py

As a next step, we'll modify views.py under app directory, HelloWorldApp:

# Create your views here.
from django.http import HttpResponse
def foo(request):
    return HttpResponse("Hello World!")

This views.py takes a request object and returns a response object.

Note that we first import the HttpResponse object from the django.http module. Each view exists within the views.py file as a series of individual functions. In our case, we only created one view - called foo. Each view takes in at least one argument - a HttpRequest object, which also lives in the django.http module. Each view must return a HttpResponse object. A simple HttpResponse object takes a string parameter representing the content of the page we wish to send to the client which is requesting the view.



HTTP_Request_HTTP_Response.png



Run the server
$ python manage.py runserver

If we type in http://localhost:8000/HelloWorldApp/, we get the successful "Hello World!":


SuccessfulHelloWorldApp.png



How it works?
  1. When we type localhost:8000/HelloWorldApp into the browser, this will send request to Django. Django framework provides a way to map HelloWorldApp to a code to do something as listed in the next steps.
  2. Django will read urls.py and look for url matching pattern.
  3. If it matches, it calls the associated function.
  4. In our case, it matches HelloWorldApp in urls.py.
  5. So, foo() in views.py is called.
  6. In views.py, we have the code to display the "Hello World!" as HttpResponse.




Summary: Basic Work Flow
  1. Creating a new Django Project

    To create the project, we need to run,
    django-admin.py startproject <project_name>
    
  2. Creating a new Django application

    1. To create a new application, we should run,
      python manage.py startapp <app_name>
      
    2. Tell our Django project about the new application by adding it to the INSTALLED_APPS tuple in our project's settings.py file.
    3. In our project urls.py file, add a mapping to the application and this info in urls.py file will be used to direct incoming URL strings to views.
    4. In our application's view.py, create the required views ensuring that they return a HttpResponse object.







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