


Python development [Django]: combined search, JSONP, XSS filtering
1. Simple implementation
Associated files:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^index.html/$',views.index), url(r'^article/(?P<article_type>\d+)-(?P<category>\d+).html/$',views.article) ] url.py
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% if kwargs.article_type == 0 %} <a href="/article/0-{{ kwargs.category }}.html">全部</a> {% else %} <a href="/article/0-{{ kwargs.category }}.html">全部</a> {% endif %} {% for row in article_type %} {% if row.id == kwargs.article_type %} <a href="/article/{{ row.id }}-{{ kwargs.category }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ row.id }}-{{ kwargs.category }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category == 0 %} <a href="/article/{{ kwargs.article_type }}-0.html">全部</a> {% else %} <a href="/article/{{ kwargs.article_type }}-0.html">全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category %} <a href="/article/{{ kwargs.article_type }}-{{ row.id }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ kwargs.article_type }}-{{ row.id }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
Database structure:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) class ArticleType(models.Model): caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) article_type = models.ForeignKey(ArticleType)
Processing files:
from . import models def article(request,*args,**kwargs): search_dict = {} for key,value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value !='0': search_dict[key] = value articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.ArticleType.objects.all() category = models.Categoery.objects.all() return render(request,'article.html',{'articles':articles, 'article_type':article_type, 'category':category , 'kwargs':kwargs})
Note: It is not necessary to implement this function Difficult, the most important thing is to clarify the ideas inside; first, determine the url access path format http://127.0.0.1:8000/article/0-0.html, the first 0 represents the article_type field, and the second 0 Indicates the category field. If it is zero, it means searching for all information in this field. Confirming this is the first step to success. There is retrieval processing on the processing file; the second key point is to generate a dictionary search_dict for related searches. If If it is 0, it means searching all; the third key point is also a very clever way, passing the parameter kwargs to the front end again, it is a stroke of genius!
2. Another attempt (loading memory tuning)
Since the ArticleType type is fixed data for the blog, it will not be changed later, so you can load the data into the memory to speed up the query
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% if kwargs.article_type_id == 0 %} <a href="/article/0-{{ kwargs.category_id }}.html">全部</a> {% else %} <a href="/article/0-{{ kwargs.category_id }}.html">全部</a> {% endif %} {% for row in article_type%} {% if row.0 == kwargs.article_type_id %} <a href="/article/{{ row.0 }}-{{ kwargs.category_id }}.html">{{ row.1 }}</a> {% else %} <a href="/article/{{ row.0 }}-{{ kwargs.category_id }}.html">{{ row.1 }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category_id == 0 %} <a href="/article/{{ kwargs.article_type_id }}-0.html">全部</a> {% else %} <a href="/article/{{ kwargs.article_type_id }}-0.html">全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category_id %} <a href="/article/{{ kwargs.article_type_id }}-{{ row.id }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ kwargs.article_type_id }}-{{ row.id }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse('Ok') from . import models def article(request,*args,**kwargs): search_dict = {} for key,value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value !='0': search_dict[key] = value print(kwargs) articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.Article.type_choice print(article_type) category = models.Categoery.objects.all() return render(request,'article.html',{'articles':articles, 'article_type':article_type, 'category':category , 'kwargs':kwargs}) 处理文件.py
Database file:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) # class ArticleType(models.Model): # caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) # article_type = models.ForeignKey(ArticleType) type_choice = [ (1,'Python'), (2,'Linux'), (3,'大数据'), (4,'架构'), ] article_type_id = models.IntegerField(choices=type_choice)
3. Use simple_tag to optimize the code
Associated files:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) class ArticleType(models.Model): caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) article_type = models.ForeignKey(ArticleType) # type_choice = [ # (1,'Python'), # (2,'Linux'), # (3,'大数据'), # (4,'架构'), # ] # article_type_id = models.IntegerField(choices=type_choice) 数据库文件.py
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse('Ok') from . import models def article(request, *args, **kwargs): search_dict = {} for key, value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value != '0': search_dict[key] = value articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.ArticleType.objects.all() print(article_type) category = models.Categoery.objects.all() return render(request, 'article.html', {'articles': articles, 'article_type': article_type, 'category': category, 'kwargs': kwargs}) 处理文件.py
{% load filter %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% filter_all kwargs 'article_type'%} {% filter_single article_type kwargs 'article_type'%} </div> <div> {% filter_all kwargs 'category'%} {% filter_single category kwargs 'category'%} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
Create templatetags directory , create the filter.py file in the directory:
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def filter_all(kwargs,type_str): print(type_str) if type_str == 'article_type': if kwargs['article_type'] == 0: tmp = '<a href = "/article/0-%s.html" class ="active" > 全部 </a>'%(kwargs['category']) else: tmp = '<a href = "/article/0-%s.html"> 全部 </a>'%(kwargs['category']) elif type_str == 'category': if kwargs['category'] == 0: tmp = '<a href = "/article/%s-0.html" class ="active" > 全部 </a>' % (kwargs['article_type']) else: tmp = '<a href = "/article/%s-0.html"> 全部 </a>' % (kwargs['article_type']) return mark_safe(tmp) @register.simple_tag() def filter_single(type_obj,kwargs,type_str): print(type_str) tmp = '' if type_str == 'article_type': for row in type_obj: if row.id == kwargs['article_type']: tag = '<a class="active" href="/article/%s-%s.html">%s</a>\n'%(row.id,kwargs['category'],row.caption) else: tag = '<a href="/article/%s-%s.html">%s</a>\n' % (row.id, kwargs['category'],row.caption) tmp +=tag elif type_str == 'category': for row in type_obj: if row.id == kwargs['category']: tag = '<a class="active" href="/article/%s-%s.html">%s</a>\n' % (kwargs['article_type'],row.id, row.caption) else: tag = '<a href="/article/%s-%s.html">%s</a>\n' % (kwargs['article_type'], row.id, row.caption) tmp += tag return mark_safe(tmp)
HTML file main content:
{% load filter %} <body> <h2>过滤条件</h2> <div class="condition"> {% filter_all kwargs 'article_type'%} {% filter_single article_type kwargs 'article_type'%} </div> <div class="condition"> {% filter_all kwargs 'category'%} {% filter_single category kwargs 'category'%} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body>
JSONP
JSONP (JSON with Padding) is a "usage mode" of JSON ”, which can be used to solve the problem of cross-domain data access by mainstream browsers. Due to the same-origin policy, generally speaking, web pages located at server1.example.com cannot communicate with servers other than server1.example.com, with the exception of the HTML

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Python development experience sharing: How to carry out version control and release management Introduction: In the Python development process, version control and release management are very important links. Through version control, we can easily track code changes, collaborate on development, resolve conflicts, etc.; and release management can help us organize the deployment, testing and release process of code to ensure the quality and stability of the code. This article will share some experiences and practices in Python development from two aspects: version control and release management. 1. Version control version control

As a high-level programming language, Python is becoming more and more popular among developers due to its advantages of being easy to learn, easy to use, and highly efficient in development. However, due to the way its garbage collection mechanism is implemented, Python is prone to memory leaks when dealing with large amounts of memory. This article will introduce the things you need to pay attention to during Python development from three aspects: common memory leak problems, causes of problems, and methods to avoid memory leaks. 1. Common memory leak problems: Memory leaks refer to the inability to release the memory space allocated by the program during operation.

Python development experience sharing: How to conduct code review and quality assurance Introduction: In the software development process, code review and quality assurance are crucial links. Good code review can improve code quality, reduce errors and defects, and improve program maintainability and scalability. This article will share the experience of code review and quality assurance in Python development from the following aspects. 1. Develop code review specifications Code review is a systematic activity that requires a comprehensive inspection and evaluation of the code. In order to standardize code review

Python is a powerful and flexible programming language that is widely used in software development in various fields. In the Python development process, it is very important to master and apply the principles of Object-Oriented Programming (OOP). This article will introduce some key Python development suggestions to help developers better grasp and apply the principles of object-oriented programming. First of all, the core idea of object-oriented programming is to divide the problem into a series of objects and

pip Domestic Source Installation Tutorial: To make your Python development smoother, specific code examples are required. In Python development, it is very common to use pip to manage third-party libraries. However, due to well-known reasons, sometimes using the official pip source directly will encounter problems such as slow download speed and inability to connect. In order to solve this problem, some excellent domestic sources of pip have emerged in China, such as Alibaba Cloud, Tencent Cloud, Douban, etc. Using these domestic sources can greatly improve download speed and improve the efficiency of Python development.

Starting from scratch, we will teach you step by step how to configure the domestic source of pip to make your Python development more efficient. During the development process of Python, we often use pip to manage third-party libraries. However, due to domestic network environment problems, using the default pip source often results in slow download speeds or even inability to connect. In order to make our Python development more efficient, it is necessary to configure a domestic source. So, let us now configure the pip domestic source step by step! First, we need to find pip

Python development is a simple yet powerful programming language that is often used to develop various types of applications. However, for beginners, there may be some challenges in project structure and module division. A good project structure and module division not only help to improve the maintainability and scalability of the code, but also improve the efficiency of team development. In this article, we will share some suggestions to help you properly plan the structure and module division of your Python project. First of all, a good project structure should be able to clearly demonstrate the project’s

Summary of Python development experience: Methods to improve code security and defense. With the development of the Internet, code security and defense have attracted more and more attention. In particular, Python, as a widely used dynamic language, also faces various potential risks. This article will summarize some methods to improve the security and defense of Python code, hoping to be helpful to Python developers. Proper use of input validation During the development process, user input may contain malicious code. To avoid this from happening, developers should
