Some examples of simplifying Python's Django framework code

Source: Internet
Author: User
Tags django website django tutorial
Despite the popularity and popularity of Django, some developers still think of her as an outdated web development framework that is only suitable for content-rich Web applications. Yet most web programs are often not rich in content, which seems to make Django seem not the best choice for the web framework.

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

Simple and clear Django

A web framework is primarily to help the Web program build the core architecture for reuse in other projects. It is on this basis that Django builds the Web program quickly. The core of Django is primarily the WSGI program, which handles HTTP requests and returns a meaningful HTTP response. She provides various tools like 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 right away, in order to enrich the Web program build experience, she provides a lot of various filters and tags to create dynamic extensible templates.


With these tools, you can easily create a simple and clear mini-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 it will give us less distraction. For example, when you are in tangled Jinja2, Mako, Genshi, Cheetah, you may already be using the template engine that Django already exists. Less entanglement allows us to enjoy the enjoyable development process more.

Train a new Django user

There is a big problem in the community of Django and other web frameworks, which is the problem of training new users. It's like a lot of Django users learn Django by creating a voting program on the Django website. Many of our sophisticated Django developers consider it a "rite of passage" into the Django community. But is it the best way to learn about Django? I don't think so.

Currently, this voting procedure has six parts. Although each part has its meaning, until the third one you can write your view and construct the HTTP reply. The simple "Hello World" program is too far away from the home page of some popular Python mini-frames (like flask and bottle). The best way to learn is when we're learning about a piece of Django without too much hindrance and can focus on interacting with requests and responses. New users can get help from other parts of the framework when building common web tasks, such as reply management, user authentication, and the built-in admin interface.


So, let's build a simplified version of the Django tutorial as we mean:

Import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import Httpresponsefrom D Jango.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 simple. This short code is all you need to run the Django project. Let's start by explaining each part of the code gradually.

First, we need to ensure that HttpResponse is introduced and returns 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. But in this streamlined tutorial, we put all the code in a Django project in a single file.

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

From django.conf.urls import patternsfrom django.http import HttpResponse def index (request):  return HttpResponse (' Powered by Django ') Urlpatterns = Patterns (",   (R ' ^$ ', index),)

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


Import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import HttpResponse Setti Ngs.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 in the example above that we have stripped those settings, and especially omitted the configuration of the database. These settings can be used as a threshold for new users, and may avoid confusion when these new users 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 barriers to work.

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

Because the structure is not generated using the Start Project command, we will discard the Manage.pyfile file. Therefore, you need to manually add the relevant Manage.pyand information:

Import sys from django.conf import settingsfrom django.conf.urls import patternsfrom django.http import Httpresponsefrom D Jango.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 launch the app from the command line:

$ python project_name.py runserver

Visit 127.0.0.1:8000 and you'll see the "Powered by Django" Page!

See here, you may have to ask: "Where are the models and views?" ”。 Let's just relax before this. Let's talk about what Django is-she's a web framework that contains a set of tools that we often need to use, and you can easily reference them in your project. Next we'll show you 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 need to add URLs and some necessary settings to let Django know where the template files are placed. Add these settings to the file.

Import osimport sys base_path = os.path.dirname (__file__) from django.conf import settingsfrom django.conf.urls import Pat Terns, Urlfrom django.core.management import execute_from_command_linefrom 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 at the top that we 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 folders. Now we can easily add a path to the template in our Template_dirs settings and begin to experience the benefits of Django's built-in tags and filters!

As you can see, by breaking down the basic part of creating a Django application into smaller parts, we can create an easier way for the built-in new user. We need to re-learn how to get Django to create a Django application without ORM and Django management. Need to recognize the built-in features of Django what they really are. They are not required when using frames, and if you feel they are not necessary, you do not lose too much. We started using the good part of Django instead of feeling its weight, just like we were learning Python's standard library. Let's start removing obsolete things and look at its source code, which is really rich in functionality.

So, based on all of this, in lightweight mode you're thinking about building something 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.