Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of python+django+mysql Development

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "python+django+mysql development case analysis", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "python+django+mysql development case analysis" bar!

Development tool: pycharm

Environment: python3.7.4 (3.6 used in the example)

Download and install pycharm

Divided into community version and professional version, one is free and the other is free.

Download Pycharm2021 cracked version

Download and install python

After installing the development tools and python environment, open pycharm, configure the python environment, and upgrade pip. As the lower version of pip affects the installation of new versions of components, it is recommended to upgrade to the latest version of pip.

I. installation and configuration environment

After configuring the python environment

Status in installation

The tips for successful installation are as follows

After success, wait for a while for the tool to process the plug-in, and then you can use the new version of pip.

Install django,pymysql in the same way

It should be noted that the dependencies of each version of the plug-in, install django and pymysql supported by your version of python

Create a django project

Right-click your project and open the terminal

Enter the following

# create a project named blogsdjango-admin.exe startproject blogs# and enter the project directory cd blogs# to create an application. Note that the application name cannot be the same as the project name python manage.py startapp blog

Pycharm setting path

Check both, then right-click the directory, add the path to the directory, and there will be no error when referencing the module

After the project is created, the directory structure is as follows

III. Development

1. Add url rout

In the urls.py file, write the following code:

From django.contrib import adminfrom django.urls import pathfrom blog.views import * urlpatterns = [path ('admin/', admin.site.urls), path (', indexes), path ('blog/', index), path (' start/', start_scrapy),]

Add application configuration to 2.Settings.py

Import pymysql # reference mysql driver pymysql.install_as_MySQLdb () ALLOWED_HOSTS = ["*"] # allow all hosts to access # Application definitionINSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles', 'blog',# add the created application module' bootstrap3' # if you need to use the bootstrap framework Need to install the django-bootstrap3 plug-in] DATABASES = {# configure database link properties # 'default': {#' ENGINE': 'django.db.backends.sqlite3', #' NAME': os.path.join (BASE_DIR, 'db.sqlite3'), #}' default': {'ENGINE':' django.db.backends.mysql' # or use mysql.connector.django 'NAME':' blog', 'USER':' root', 'PASSWORD':' @ bjive321', 'HOST':' 59.110.138.8, 'PORT':' 3306,}}

3. Write models

From django.db import models# Create your models here.class Blog (models.Model): title = models.CharField (u 'title', max_length=64) content = models.TextField (u 'content', default= "") update_time = models.DateTimeField (u 'update time', auto_now=True) pub_date = models.DateField (u 'release time') author = models.CharField (u 'author', max_length=64 Default=None) # update_time.editable = True # content shown in the list def _ _ str__ (self): return "title: {}, word count: {}, summary: {}" .format (self.title, len (self.content) Self.content [: 18]) class Spider (models.Model): # Custom primary key # id = models.CharField (primary_key=True) date = models.DateField (u 'date') open = models.DecimalField (u 'opening price', max_digits=8, decimal_places=2) close = models.DecimalField (u 'closing price', max_digits=8, decimal_places=2) height = models.DecimalField (u 'highest price', max_digits=8 Decimal_places=2) low = models.DecimalField (u 'lowest price', max_digits=8, decimal_places=2) updownd = models.DecimalField (u 'range', max_digits=8, decimal_places=2) turnrate = models.DecimalField (u 'turnover rate', max_digits=8, decimal_places=2) count = models.DecimalField (u 'total price', max_digits=8, decimal_places=2)

4. Configure the extension of the admin.py background management function to register the developed modules in the admin background management, which can automatically give the ability to add, delete, modify and query.

I have added two functions, one blog management and one crawler management (modify, view and delete the crawled content, etc.)

From django.contrib import adminfrom blog.models import Blog, Spiderclass ContactAdmin (admin.ModelAdmin): # when adding content, store the login account in the specified field, which should be reserved in models Here is author def save_model (self, request, obj, form, change): if change: # the update operation returns true obj.save () else: # otherwise it is added obj.author = request.user obj.save () # set the author field read-only readonly_fields = ("author",) # filter You can only view the content created by the operator def get_queryset (self, request): qs = super (ContactAdmin, self). Get_queryset (request) if request.user.is_superuser: return qs return qs.filter (author=request.user) # listdisplay sets the field to be displayed in the list (the id field is the default primary key for the Django model) list_display = ('title',' update_time') 'pub_date',' author') # list search_fields = ('title',' content',) # if there is only one value Must end with a comma to prove that it is list or tuple # list_per_page sets how many records are displayed per page. Default is 100th list_per_page = 5 # ordering sets the default sort field Negative sign indicates descending sort ordering = ('- update_time',) # list_editable setting default editable field. The first field does not allow editing list_editable = ['pub_date',] # fk_fields setting to display foreign key field # fk_fields = (' machine_room_id',) date_hierarchy = 'pub_date'class SpiderAdmin (admin.ModelAdmin): list_display = (' date', 'open') 'close',' height', 'low',' updownd', 'turnrate',' count') # list date_hierarchy = 'date' # list_per_page sets how many records are displayed per page The default is list_per_page = 2percent Register your models here.admin.site.register (Blog, ContactAdmin) admin.site.register (Spider, SpiderAdmin) # set the title of the login window admin.site.site_header = 'very cool system' # set the tab title admin.site.site_title = 'blockbuster'

4. Initialize admin and create blog and spider tables

$python manage.py migrate # create table structure, default create admin module table $python manage.py makemigrations blog # Let Django know that we have some changes in our model $python manage.py migrate blog # create custom table structure $python manage.py createsuperuser # create background administrator account

5. Write views.py

Import base64from io import BytesIOimport requestsfrom django.http import JsonResponsefrom django.shortcuts import renderimport markdown# Create your views here.import blog.models as mimport pandas as pdimport matplotlibfrom matplotlib import pyplot as plt# query # models.UserInfo.objects.all () # models.UserInfo.objects.all (). Values ('user') # take only user columns # models.UserInfo.objects.all (). Values_list (' id','user') # fetch id and user columns And generate a list # models.UserInfo.objects.get (id=1) # models.UserInfo.objects.get (user='yangmv') # add # models.UserInfo.objects.create (user='yangmv',pwd='123456') # or # obj = models.UserInfo (user='yangmv',pwd='123456') # obj.save () # or # dic = {'user':'yangmv' 'pwd':'123456'} # models.UserInfo.objects.create (* * dic) # delete # models.UserInfo.objects.filter (id=1). Delete () # change # models.UserInfo.objects.filter (user='yangmv') .update (pwd='520') # or # obj = models.UserInfo.objects.get (user='yangmv') # obj.pwd =' 520 obj.save () def index (request): I = request.GET.get ('id') # postdata = request.POST ['id'] blog = m.Blog.objects.get (id=i) blog_content = markdown.markdown (blog.content) spider = m.Spider.objects.all (). Values () plot_data = showMatplot (pd.DataFrame (spider) imb = base64.b64encode (plot_data) # encode plot_data ims = imb.decode () imd = _ "data:image/png Base64, "+ ims return render (request," blog.html ", {'blog': blog,' blog_content': blog_content, 'img': imd}) def indexes (request): blogs = m.Blog.objects.all () return render (request," blogs.html ", {' blogs': blogs}) # icon embedded in django page def showMatplot (df): plt.figure (figsize= (12) ) # set the image size plt.subplot (212) # layout the second col of two rows and one column = ['date',' open', 'close',' height', 'low',' updownd', 'count'] df = df.astype ({' open': 'float',' close': 'float',' height': 'float',' low': 'float' 'updownd':' float', 'count':' float'}) df = pd.DataFrame (df Columns=col) # print (df) # print ("*" * 40) # # corr can only calculate the correlation of numerical data # print (df.corr ()) x = pd.to_datetime (df ['date']) y1 = df ["open"] y2 = df ["close"] y3 = df ["height"] y4 = df ["low"] plt.plot (x, y1, label='open', linestyle='-' Plt.plot (x, y2, label='close', linestyle='--', cymbals, linewidth=1) plt.plot (x, y3, label='height', linestyle=':', cymbals, linewidth=1) plt.plot (x, y4, label='low', linestyle='-.', cymbals, linewidth=1) plt.legend () plt.subplot (211) # layout two rows and one column first df1 = df.sort_values (by='date' Ascending=True) # df1 = df1.iloc [30:] col = ["date", "close"] close = pd.DataFrame (df1, columns=col) data = cal_macd_system (close, 12,26,9) x = pd.to_datetime (data ['date']) # y = pd.to_numeric (data ["close"]) y1 = data ["macd"] # plt.plot (x, y, label= "k") plt.plot (x, y1) Label= "macd") plt.title ("company stock", fontproperties=zhfont1, fontsize=15) plt.legend () buffer = BytesIO () plt.savefig (buffer) plot_data = buffer.getvalue () return plot_data# download fonts into the project directory The solution icon shows zhfont1 = matplotlib.font_manager.FontProperties (fname= "FZSTK.TTF") # macd indicator algorithm def cal_macd_system (data, short_,long_,m):''data is the standard dataframe short_,long_,m with high opening and low closing volume, and the return value of the three parameters is macd, which contains raw data and diff,dea. Dataframe''data [' diff'] = data ['close'] .ewm (adjust=False, alpha=2 / (short_ + 1), ignore_na=True). Mean () -\ data [' close'] .ewm (adjust=False, alpha=2 / (long_ + 1), ignore_na=True). Mean () data ['dea'] = data [' diff'] .ewm (adjust=False, alpha=2 / (m + 1) Ignore_na=True) .mean () data ['macd'] = 2 * (data [' diff']-data ['dea']) return data# draws macd index curve def macdview (df): df1 = df.sort_values (by='date', ascending=True) # df1 = df1.iloc [30:] col = ["date", "close"] close = pd.DataFrame (df1, columns=col) data = cal_macd_system (close, 12,26) 9) x = pd.to_datetime (data ['date']) # y = pd.to_numeric (data ["close"]) y1 = data ["macd"] # plt.plot (x, y, label= "k") plt.plot (x, y1, label= "macd") plt.title ("company stock", fontproperties=zhfont1 Fontsize=15) # plt.legend () buffer = BytesIO () buffer.flush () plt.savefig (buffer) plot_data = buffer.getvalue () buffer.close () return plot_data# online launch crawler def start_scrapy (request): # get page parameters To distinguish whether the request type is POST or GET, different requests use different methods to receive the parameter year = request.POST.get ('year') jd = request.POST.get (' jd') url = 'http://127.0.0.1:6800/schedule.json' # spider is the name returned by executing scrapy list. Parameter problem: in addition to the parameters of built-in key, such as project,spider, etc. Other parameters are received by the kwargs of the crawler initialization function # while jobid is also received by kwargs. * * kwargs is a typical parameter of the receiving word, data= {'project':' pachong', 'spider':' pachong_spider', 'year': year with key value,' jd': jd} print (requests.post (url=url, data=data)) return JsonResponse ({'result':' ok'})

Under the created application, create 2 folders named static and templates. The name must be this. Static is to put static resources such as css,js,img, and templates stores template page files, html, etc.

If you want to customize the path, you need to configure your path to the environment in settings.py (please configure Baidu for specific configuration)

5. Run the service in the terminal:

$python manage.py runserver 8080 (default 8000 if port number is not specified)

The above is my first entry-level django project development process, in order to record, encourage later learning! The code that will be sorted out and learned by the crawler will also be recorded.

Project source code: pystudy_jb51.rar

So far, this is the end of this article on python+django+mysql development practice (with demo). For more related python django mysql development content, please search previous articles or continue to browse the following related articles. I hope you will support me in the future!

At this point, I believe you have a deeper understanding of the "python+django+mysql development case analysis", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report