本文共 5940 字,大约阅读时间需要 19 分钟。
import difflibdef read_file(file): try: with open(file, "r", encoding="utf8") as fp: return fp.readlines() except IOError: print("ERROR: 没有找到文件:%s或读取文件失败!" % file)def compare_file(file1, file2, output): content1 = read_file(file1) content2 = read_file(file2) d = difflib.HtmlDiff() result = d.make_file(content1, content2) with open(output, 'w') as f: f.writelines(result)if __name__=="__main__": file1 = "file1.txt" file2 = "file2.txt" compare_file(file1, file2, "result.html")
app.py
from django.apps import AppConfigclass appConfig(AppConfig): name = 'compare'
views.py
from django.shortcuts import renderimport difflibfrom bs4 import BeautifulSoupimport osimport webbrowser as webproDir = os.path.join(os.path.split(os.path.dirname(__file__))[0],"templates")#打开初始页面web.open("http://127.0.0.1:9000/compare")#定义比较文本方法def compare_file(content1, content2, result): content1 = content1.split("\n") content2 = content2.split("\n") b = difflib.HtmlDiff() r = b.make_file(fromlines=content1, tolines=content2) sp=BeautifulSoup(r, 'lxml') style = sp.find('style') style.string += ".nowrap{width:50%;word-break:break-all;}" html = sp.prettify() html = html.replace('nowrap="nowrap"', 'class="nowrap"') with open(result, 'w',encoding="utf8") as f: f.writelines(html)#定义初始接口 def compare(req): return render(req,"index.html")#定义展示比较结果接口def result(req): body = req.POST content1 = body.get("content1") content2 = body.get("content2") file_path = os.path.join(proDir, "test.html") compare_file(content1, content2, file_path) return render(req,"test.html")
settings.py
"""Django settings for blog_demo project.Generated by 'django-admin startproject' using Django 2.2.7.For more information on this file, seehttps://docs.djangoproject.com/en/2.2/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/2.2/ref/settings/"""import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'qd_nl4f+v7@_5l1o^4zoqtnitvdn11z+++$vkky*u)t0k*iyeo'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "compare", #新增]MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',# 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'MyCompare.urls'TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]WSGI_APPLICATION = 'MyCompare.wsgi.application'# Database# https://docs.djangoproject.com/en/2.2/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Password validation# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },]# Internationalization# https://docs.djangoproject.com/en/2.2/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/2.2/howto/static-files/STATIC_URL = '/static/'
urls.py
from django.contrib import adminfrom django.urls import pathfrom compare.views import *urlpatterns = [ path('compare',compare), path('result',result)]
wsgi.py
import osfrom django.core.wsgi import get_wsgi_applicationos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyCompare.settings')application = get_wsgi_application()
templates.index.html
Compare
manage.py
#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""import osimport sysdef main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyCompare.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)if __name__ == '__main__': main()
startApp.py,用于启动应用
import osos.system("python manage.py runserver 9000")
1.启动startApp.py
2.查看结果转载地址:http://etmji.baihongyu.com/