Some examples of simplifying Python's Django framework code _python

Source: Internet
Author: User
Tags django tutorial

Despite the popularity and popularity of Django, some developers still think of her as an outdated web development framework for content-rich Web applications only. However, most web programs are often not rich content, which seems to make Django not the best choice for the web framework.

So let's take a moment to get to know her again from the current web development practice.

Simple and clear Django

A web framework is primarily designed to help web programs build the core architecture for reuse in other projects. This is the basis for Django to quickly build Web programs. The core of Django is primarily the WSGI program, which handles HTTP requests and returns a meaningful HTTP response. She provides a variety of tools, such as generating URL routing, cookie processing, parsing form data, and uploading files.

Also, Django creates a dynamic template engine for HTTP replies. You can use it immediately, in order to enrich the Web application build experience, she provides a lot of various filters and tags to create dynamic extensible template.


With these tools, you can easily create a simple and clear micro-frame in your Django project.

We know that some people like to build their own wheels. We're not talking about degrading this behavior, but using Django to develop will give us less disruption. For example, when you're in a tangle of Jinja2, Mako, Genshi, Cheetah, you're probably already using the template engine that Django already exists. Less entanglements allow us to enjoy the enjoyable development process more.

Training New Django users

One big problem with Django and other web framework communities is the training of new users. Just as many Django users learn Django by creating a voting program on the Django Web site. Many of our sophisticated Django developers think of it as a "rite of passage" into the Django community. But is it the best way to learn about Django? I don't think so.

At present, this voting procedure has six parts. Although each part has its meaning, it is not until the third that you can write your view and construct an HTTP response. The relatively simple "Hello World" program is far from the home page of some popular Python micro-frameworks like flask and bottle. The best way to learn is when we learn a certain piece of Django without too much hindrance and can focus on the interaction between the request and the response. New users can get help in building common web tasks from other parts of the framework, such as reply management, user authentication, and the built-in admin interface.


So, to build a simplified version of the Django tutorial, as we're saying:

Import SYS from
 
django.conf import settings from
django.conf.urls import patterns from
django.http Import HttpResponse from
django.core.management import execute_from_command_line
 
settings.configure (
  debug= True,
  secret_key= ' Placerandomsecretkeyhere ',
  root_urlconf=sys.modules[__name__],
 
def index ( Request): Return
  HttpResponse (' Powered by Django ')
 
urlpatterns = Patterns (', 
  (R ' ^$ ', index)
 
if __name__ = = "__main__":
  execute_from_command_line (SYS.ARGV)

It's easy. This short piece of code is all that is needed to run the Django project. Let's start with a step-by-step explanation of the various parts of the code.

First, we need to make sure that we introduce HttpResponse and return what we want to return.

From django.http import HttpResponse
 
def index (request): Return
  HttpResponse (' Powered by Django ')

In general, this code should be inside the view.py. However, in this simplified version of the tutorial, we put all the code in the Django project in a single file.

The perfect link between the current part of the application and the next part is the linking structure. The above code expects such a URL index, so we need to create one for it.

From django.conf.urls import patterns to
django.http import httpresponse
 
def index (request):
  return HttpResponse (' Powered by Django ')
 
urlpatterns = Patterns (', 
  (R ' ^$ ', index)

With just 7 lines of code above, we've built the foundation for our applications to run on Django! Now let's do some basic setup so that the application can be executed.


Import SYS from
 
django.conf import settings from
django.conf.urls import patterns from
django.http Import HttpResponse
 
settings.configure (
  debug=true,
  secret_key= ' Placerandomsecretkeyhere ',
  ROOT_ URLCONF=SYS.MODULES[__NAME__],
 
def index (request): Return
  HttpResponse (' Powered by Django ')
 
Urlpatterns = Patterns (', 
  (R ' ^$ ', index),
)

You may have found that in the above example, we have stripped out those settings and, in particular, omitted the configuration of the database. These settings can be used as a threshold for new users to avoid confusion when they try to determine what database to use. When developing a project, we want to make sure that our work is focused on specific parts, thus reducing the obstacles in our work.

Note: A random Secret_key is set in the Settings.configure file to protect session and Cross-site request forgery (CSRF).

Because the start Project command was not used to build the structure, we lost the Manage.pyfile file. Therefore, you need to manually add the relevant Manage.pyand information:

Import SYS from
 
django.conf import settings from
django.conf.urls import patterns from
django.http Import HttpResponse from
django.core.management import execute_from_command_line
 
settings.configure (
  debug= True,
  secret_key= ' Placerandomsecretkeyhere ',
  root_urlconf=sys.modules[__name__],
 
def index ( Request): Return
  HttpResponse (' Powered by Django ')
 
urlpatterns = Patterns (', 
  (R ' ^$ ', index)
 
if __name__ = = "__main__":
  execute_from_command_line (SYS.ARGV)

You can now start the application from the command line:

$ python project_name.py runserver

When you visit 127.0.0.1:8000, you will see the "Powered by Django" Page!

See here, you might ask: "Where are the models and views?" ”。 Let's just relax a little bit before that. Let's talk about what Django is--she's a web framework that contains a series of tools that we often need to use, and you can easily reference them in your project. Next we'll explain how to introduce these tools. Building a template is a good way to do it. Let's get started.

Before adding a template file, we add URLs and some necessary settings to let Django know where the template files are placed. Add these settings to the file.

Import OS
import sys
 
base_path = os.path.dirname (__file__) from
 
django.conf import settings
from Django.conf.urls import patterns, url from
django.core.management import Execute_from_command_line
from Django.shortcuts Import Render
 
settings.configure (
  debug=true,
  secret_key= ' Placerandomsecretkeyhere ') ,
  root_urlconf=sys.modules[__name__],
  template_dirs= (
    os.path.join (Base_path, ' templates '), )
 
def index (request): Return
  render (request, ' index.html ', {' request ': request})
 
Urlpatterns = Patterns (', 
  url (r ' ^$ ', index, name= ' index '),
 
if __name__ = "__main__":
  execute_ From_command_line (SYS.ARGV)

You will notice that at the top we have added the Os.path Python module to the import. By doing this, we have created an easy way for new users to point to their project folder. Now we can easily add a path to the template in our Template_dirs settings and begin to experience the advantages of Django's built-in tags and filters!

As you can see, by breaking down the basics of creating a Django application into smaller parts, we can create a simpler way to build new users. We need to learn how to get Django to create Django applications without ORM and Django management. Need to recognize the built-in features of Django what they really are. They are not necessary when using frames, and if you feel they are not necessary, you are not losing too much. We started using the good part of Django instead of feeling its weight, just as we learned the standard library of Python. Let's start by removing outdated things, and looking at its source, the function is really very rich.

So, based on all this, in the lightweight model, are you considering building applications that can be developed?

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.