1. 簡単な実装
関連ファイル:
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</category></article_type>rreee
データベース構造:
nbsp;html> <meta> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> <h2 id="过滤条件">过滤条件</h2> <div> {% if kwargs.article_type == 0 %} <a>全部</a> {% else %} <a>全部</a> {% endif %} {% for row in article_type %} {% if row.id == kwargs.article_type %} <a>{{ row.caption }}</a> {% else %} <a>{{ row.caption }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category == 0 %} <a>全部</a> {% else %} <a>全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category %} <a>{{ row.caption }}</a> {% else %} <a>{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2 id="查询结果">查询结果</h2>
-
{% for row in articles %}
- {{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}] {% endfor %}
処理ファイル:
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)
注: この関数を実装するのに最も重要なことは、最初に内部のアイデアを明確にすることです。 URL アクセス パスの形式は http://127.0.0.1:8000/article/0-0.html です。最初の 0 は、article_type フィールドを表し、2 番目の 0 は、0 の場合、検索を意味します。このフィールドのすべての情報を確認します。これが成功への最初のステップであり、検索処理でファイルを処理します。2 番目のキー ポイントは、関連する検索用の辞書 search_dict を生成することです。これが 0 の場合は、3 番目のキーをすべて検索することを意味します。ポイントも非常に賢い方法で、パラメーター kwargs をフロントエンドに再度渡します。なんと天才的なことでしょう。
2. 別の試み (メモリチューニングのロード)
ArticleType タイプはブログの固定データなので、後で変更されないように、クエリを高速化するためにデータをメモリにロードできます
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})
nbsp;html> <meta> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> <h2 id="过滤条件">过滤条件</h2> <div> {% if kwargs.article_type_id == 0 %} <a>全部</a> {% else %} <a>全部</a> {% endif %} {% for row in article_type%} {% if row.0 == kwargs.article_type_id %} <a>{{ row.1 }}</a> {% else %} <a>{{ row.1 }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category_id == 0 %} <a>全部</a> {% else %} <a>全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category_id %} <a>{{ row.caption }}</a> {% else %} <a>{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2 id="查询结果">查询结果</h2>
-
{% for row in articles %}
- {{ row.id }}-{{ row.title }}------[{{ row.article_type }}]-[{{ row.category.caption }}] {% endfor %}
データベース。ファイル:
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
3. simple_tag を使用してコードを最適化します
関連ファイル:
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)
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
templatetags ディレクトリを作成し、そのディレクトリに filter.py ファイルを作成します:
{% load filter %} nbsp;html> <meta> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> <h2 id="过滤条件">过滤条件</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 id="查询结果">查询结果</h2>
-
{% for row in articles %}
- {{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}] {% endfor %}
HTML ファイルのメインコンテンツ:
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> 全部 </a>'%(kwargs['category']) else: tmp = '<a> 全部 </a>'%(kwargs['category']) elif type_str == 'category': if kwargs['category'] == 0: tmp = '<a> 全部 </a>' % (kwargs['article_type']) else: tmp = '<a> 全部 </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>%s</a>\n'%(row.id,kwargs['category'],row.caption) else: tag = '<a>%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>%s</a>\n' % (kwargs['article_type'],row.id, row.caption) else: tag = '<a>%s</a>\n' % (kwargs['article_type'], row.id, row.caption) tmp += tag return mark_safe(tmp)
JSONP
JSONP (JSON with Padding) は、主流ブラウザによるクロスドメイン データ アクセスの問題を解決するために使用できる JSON の「使用パターン」です。同一オリジン ポリシーにより、一般に、server1.example.com にある Web ページは、HTML の <script> 要素を除き、server1.example.com 以外のサーバーと通信できません。 <script> 要素のこのオープン ポリシーを使用すると、Web ページは他のソースから動的に生成された JSON データを取得できます。この使用パターンは JSONP と呼ばれます。 JSONP でキャプチャされたデータは JSON ではなく、JSON パーサーで解析されるのではなく、JavaScript インタープリターで実行される任意の JavaScript です。 </script>
原則:
- スクリプトタグを作成します
- src = リモートアドレス
- 返されるデータは js 形式である必要があります
- GET リクエストのみを送信できます
1. 同一生成元ポリシーとは何ですか?
処理ファイル:
{% load filter %} <h2 id="过滤条件">过滤条件</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 id="查询结果">查询结果</h2>
-
{% for row in articles %}
- {{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}] {% endfor %}
HTML ファイル:
import requests def jsonp(request): # 获取url信息 response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301') response.encoding = 'utf-8' # 进行编码 return render(request,'jsonp.html',{'result':response.text}) # response.text 请求内容
注: js をクリックして結果を直接取得すると、ブラウザは http://127.0.0.1:8000 から送信された情報のみを受け入れるため、次のエラー メッセージが表示されます。 、天気予報 Web サイトから送信された情報が直接ブロックされます。これを解決する方法はありますか。
<body> <h1 id="后台获取的结果">后台获取的结果</h1> {{ result }} <h1 id="js直接获取结果">js直接获取结果</h1> <input type="button" value="获取数据" onclick="getContent();" /> <div id="container"></div> <script src="/static/jquery-1.8.2.js"></script> <script> function getContent() { var xhr = new XMLHttpRequest(); // 创建对象 xhr.open('GET', 'http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301'); // GET方式打开 xhr.onreadystatechange = function () { // 收到返回值时执行 console.log(xhr.responseText); }; xhr.send() // 发送 } </script> </body>
2. scriptタグのsrc属性を上手に使おう
scriptタグは同一オリジンポリシーの影響を受けない
処理ファイル:
XMLHttpRequest cannot load http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access.
HTMLファイル:
import requests def jsonp(request): # 获取url信息 response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301') response.encoding = 'utf-8' # 进行编码 return render(request,'jsonp.html',{'result':response.text}) # response.text 请求内容 def jsonp_api(request): return HttpResponse('alert(123)')
注意:便宜上js をリクエストするとき、リクエストはまだ現在のプログラム URL に対するものです。上記のコードを実行すると、魔法のような状況が発生し、スクリプトが情報を正常に取得したことを示す 123 の情報が表示されます
3. フロントエンドとバックエンドを少し変更して、使用法をより動的にします
処理ファイル:
<body> <h1 id="后台获取的结果">后台获取的结果</h1> {{ result }} <h1 id="js直接获取结果">js直接获取结果</h1> <input type="button" value="获取数据" onclick="getContent();" /> <div id="container"></div> <script> function getContent() { var tag = document.createElement('script'); tag.src = '/jsonp_api.html'; document.head.appendChild(tag); // document.head.removeChild(tag); } </script> </body>
HTML ファイル:
def jsonp(request): return render(request,'jsonp.html') # response.text 请求内容 def jsonp_api(request): func = request.GET.get('callback') # 获取用户callback参数 content = '%s(10000)'%func # 执行func(10000)函数 return HttpResponse(content)
注: js リクエストを送信するときは、コールバック パラメーターを取得し、それに対応するメソッドを定義します。バックグラウンドはこのメソッドにデータを渡して実行します。印刷やポップアップ ボックスの場合は、ユーザー自身のニーズに応じて、jsonp の実装プロセスが上記のコードの実装になります。 4. サンプルアプリケーション + ajax
処理ファイル:
<body> <h1 id="后台获取的结果">后台获取的结果</h1> {{ result }} <h1 id="js直接获取结果">js直接获取结果</h1> <input type="button" value="获取数据" onclick="getContent();" /> <div id="container"></div> <script> function getContent() { var tag = document.createElement('script'); tag.src = '/jsonp_api.html?callback=list'; // 自定义callback参数,与后台达成默契 document.head.appendChild(tag); // document.head.removeChild(tag); } function list(arg){ // 自定义函数与callback=list相对应 alert(arg); } </script> </body>
HTML ファイル:
import requests def jsonp(request): response = requests.get('http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403') response.encoding = 'utf-8' # 进行编码 return render(request, 'jsonp.html', {'result': response.text}) # response.text 请求内容
<body> <h1 id="后台获取的结果">后台获取的结果</h1> {{ result }} <h1 id="js直接获取结果">js直接获取结果</h1> <input type="button" value="获取数据" onclick="getContent();" /> <div id="container"></div> <script src="/static/jquery-1.8.2.js"></script> <script> function getContent() { $.ajax({ url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403', type: 'POST', dataType: 'jsonp', // 即使写的type是POST也是按照GET请求发送 jsonp: 'callback', jsonpCallback: 'list' }); } function list(arg){ // 自定义函数与callback=list相对应 console.log(arg); var data = arg['data']; for(k in data){ var tr = document.createElement('td'); var week = data[k]['week']; var list = data[k]['list']; tr.textContent =week document.body.appendChild(tr); console.log(week); for(i in list){ var name = list[i]['name']; console.log(name) }}} </script> </body>
注: 実装済み 処理はNo.3さんが書いたコードと全く同じです。スクリプトも作成して削除しています
詳細 Python 開発 [Django]: 結合検索、JSONP、XSS フィルタリング関連記事、PHP 中国語 Web サイトにご注意ください。

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 中国語版
中国語版、とても使いやすい

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

ホットトピック









