Python Flask音乐网:实现热门歌手列表

来自CloudWiki
跳转至: 导航搜索

获取热门歌手数据

插入歌手数据

数据来源于表 artist表,

如果isHot字段的值为1,则表示这条记录为热门歌手。

INSERT INTO `artist` VALUES ('16', 'Eminem', '2', '4.jpg', '1');
INSERT INTO `artist` VALUES ('17', 'Avril Lavigne', '2', '5.jpg', '1');
INSERT INTO `artist` VALUES ('18', 'Westlife', '2', '6.jpg', '1');
INSERT INTO `artist` VALUES ('19', '久石譲', '3', '7.jpg', '1');
INSERT INTO `artist` VALUES ('20', '小林未郁', '3', '8.jpg', '1');
INSERT INTO `artist` VALUES ('21', 'Annabel', '3', '9.jpg', '1');
INSERT INTO `artist` VALUES ('22', 'G-Drago', '4', '10.jpg', '1');
INSERT INTO `artist` VALUES ('23', 'Gary', '4', '11.jpg', '1');
INSERT INTO `artist` VALUES ('24', '金泰妍', '4', '12.jpg', '1');
INSERT INTO `artist` VALUES ('25', '艾力·阿克苏巴', '5', '13.jpg', '1');
INSERT INTO `artist` VALUES ('26', '邓泰山', '5', '14.jpg', '1');
INSERT INTO `artist` VALUES ('27', 'Dome Pakor', '1', '15.jpg', '1');
INSERT INTO `artist` VALUES ('28', '刘德华', '1', '16.jpg', '1');
INSERT INTO `artist` VALUES ('29', '张学友', '1', '18.jpg', '0');
INSERT INTO `artist` VALUES ('30', '张信哲', '1', '张信哲.jpg', '0');

创建主页 蓝图

创建蓝图

通常,将蓝图放在一个单独的包里。

在app目录下 创建一个”home"子目录,并创建一个__init__.py 文件:

home/init.py

创建了一个蓝图对象home,使用起来类似app对象,可以有自己的路由home.route

Blueprint(home,__name__,url_prefix)第一个参数指定了蓝图的名称,第2个参数指定了蓝图所在的模块名,第3个参数指定了路由网址。

from flask import Blueprint

home = Blueprint('home', __name__, url_prefix='/home')
from . import views

home/views.py

# home模块
from app.home import home


# home模块
@home.route("/contentFrame")
def contentFrame():
    """
    主页面
    """
    #hot_artist = Artist.query.filter_by(isHot=1).limit(12).all()                              # 获取歌手数据
    #hot_song = Song.query.order_by(Song.hits.desc()).limit(10).all()                          # 获取歌曲数据
    #return render_template('home/contentFrame.html',hot_artist=hot_artist,hot_song=hot_song) # 渲染模板
    return "hot_artist"

注册并使用蓝图

创建完蓝图之后,需要注册蓝图。在Flask主程序中,使用"app.register_blueprint()"方法即可。

manager.py:

from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy

app = app = Flask(__name__,template_folder='app/templates', static_folder="app/static")  # 创建一个Flask app对象 
# 数据库链接的配置,此项必须,格式为(数据库+驱动://用户名:密码@数据库主机地址:端口/数据库名称)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:000000@localhost:3306/music'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 跟踪对象的修改,在本例中用不到调高运行效率,所以设置为False

#注册并使用蓝图
from app.home import home
#app.register_blueprint(admin_blue)
app.register_blueprint(home)

db = SQLAlchemy(app=app)  # 为哪个Flask app对象创建SQLAlchemy对象,赋值为db
manager = Manager(app=app)  # 初始化manager模块

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    manager.run()  # 运行服务器

效果图

运行py -3.7 manager.py runserver

之后在浏览器输入:http://127.0.0.1:5000/home/contentFrame

Python22020103.png

改进:加入模板

修改视图层

home/views.py:

修改contentFrame()函数,同时根据渲染需要,增加artistList()和artist()两个函数。

# home模块
from app.home import home

#from app import db
#from app.home.forms import LoginForm,RegisterForm,SuggetionForm
from app.models import User ,Artist,Song,Collect
from flask import render_template, url_for, redirect, flash, session, request,jsonify
from werkzeug.security import generate_password_hash
from functools import wraps

# home模块
@home.route("/contentFrame")
def contentFrame():
    """
    主页面
    """
    hot_artist = Artist.query.filter_by(isHot=1).limit(12).all()                              # 获取歌手数据
    hot_song = Song.query.order_by(Song.hits.desc()).limit(10).all()                          # 获取歌曲数据
    return render_template('home/contentFrame.html',hot_artist=hot_artist,hot_song=hot_song) # 渲染模板
    # return "hot_artist"

@home.route('/artist_list')
def artistList():
    '''
    歌手列表
    '''
    type = request.args.get('type',0,type=int)
    page = request.args.get('page',type=int)  # 获取page参数值
    if type:
        page_data = Artist.query.filter_by(style=type).paginate(page=page, per_page=10)
    else:
        page_data = Artist.query.paginate(page=page, per_page=10)
    return render_template('home/artistList.html', page_data=page_data,type=type)  # 渲染模板

@home.route("/artist/<int:id>")
def artist(id=None):
    """
    歌手页
    """
    song = Song.query.join(Artist,Song.singer==Artist.artistName).filter(Artist.id==id).all()
    hot_artist = Artist.query.limit(6).all()
    return render_template('home/artist.html',song=song,hot_artist=hot_artist) # 渲染模板


编辑模板文件

app/templates/home/contentFrame.html:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf8">
	<title>甜橙云音乐</title>
	<link href="{{ url_for('static',filename='css/pt_discover_index.css')}}" type="text/css" rel="stylesheet">
	<script src="{{ url_for('static',filename='js/jQuery-2.2.0.min.js')}}" type="text/javascript"></script>
	<script src="{{ url_for('static',filename='js/jsArr01.js')}}" type="text/javascript"></script>
	<style>
.slideshow .nivoSlider .nivo-directionNav a {
    width: 40px;
    height: 76px;
    <!--background: url(../images/arrow-prev.png) no-repeat center center #030303;-->
    top: 50%;
    margin-top: -38px;
    opacity: 0.5;
    filter: alpha(opacity=50)
}

.slideshow .nivoSlider .nivo-directionNav a.nivo-nextNav {
    background-image: url(../images/arrow-next.png)
}
.slideshow .nivo-directionNav a:hover {
    background-color: #0885B1;
    opacity: 5;
    filter: alpha(opacity=100)
}

.nivo-controlNav {
    display: none
}
.nivoSlider {
    position: relative
}

.nivoSlider img {
    left: 0;
    position: absolute;
    top: 0
}

.nivoSlider a.nivo-imageLink {
    border: 0 none;
    display: none;
    height: 100%;
    left: 0;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 6
}

.nivo-slice {
    display: block;
    height: 100%;
    position: absolute;
    z-index: 5
}

.nivo-box {
    display: block;
    position: absolute;
    z-index: 5
}

.nivo-caption {
    background: none repeat scroll 0 0 #000;
    bottom: 0;
    color: #fff;
    left: 0;
    opacity: 0.8;
    position: absolute;
    width: 100%;
    z-index: 8
}

.nivo-caption p {
    margin: 0;
    padding: 5px
}

.nivo-caption a {
    display: inline !important
}

.nivo-html-caption {
    display: none
}

.nivo-directionNav a {
    cursor: pointer;
    position: absolute;
    top: 45%;
    z-index: 9
}

.nivo-prevNav {
    left: 0
}

.nivo-nextNav {
    right: 0
}

.nivo-controlNav a {
    cursor: pointer;
    position: relative;
    z-index: 9
}

.nivo-controlNav a.active {
    font-weight: bold
}

.slideshow .nivoSlider {

    margin-bottom: 20px;
    position: relative
}


.slideshow .nivoSlider img {
    display: none;
    left: 0;
    position: absolute;
    top: 0px
    display: block;
    width: 100%;
    left: 1px !important;
    top: 1px !important
}
.slideshow .nivoSlider a {
    border: 0 none;
    display: block
}

.slideshow .nivo-controlNav {
    bottom: 5px;
    height: 22px;
    position: absolute;
    right: 10px;
    text-align: center;
    z-index: 99
}

.slideshow .nivo-controlNav a {

    border: 0 none;
    display: block;
    float: left;
    height: 22px;
    margin-right: 3px;
    text-indent: -9999px;
    vertical-align: top;
    width: 22px
}

.slideshow .nivo-controlNav a.active {
    background-position: 0 -22px
}

.slideshow .nivo-directionNav a {
    border: 0 none;
    display: block;
    height: 30px;
    text-indent: -9999px;
    width: 30px
}

.slideshow a.nivo-nextNav {
    background-position: -30px 0;
    right: 15px
}

.slideshow a.nivo-prevNav {
    left: 15px
}

.slideshow .nivo-caption {
    font-family: Helvetica, Arial, sans-serif;
    text-shadow: none
}

.slideshow .nivo-caption a {
    color: #efe9d1;
    text-decoration: underline
}
.slideshow > div {
    height: 345px !important;
    width: 850px
}
	</style>
</head>
	<body id="auto-id-hmxzivBOqt0HedNm" style="background: url('../../static/image/bg.jpg') no-repeat">
		<div data-module="discover" data-sub="discover" id="g_top"
			class="m-top">
			 
		</div>
		<div id="g_nav" class="m-subnav">
			 
		</div>
		<div class="n-ban d-flag" id="index-banner"
			style="background-image: url('../../static/image/bg.jpg'); background-repeat: no-repeat;">
			<div class="wrap">
				<div class="ban f-pr" style="z-index: 10;">
					<div id="slidershow" class="nivoSlider">
						<a href="#" class="nivo-imageLink" style="display: block;">
							<img src="{{url_for('static',filename='image/slider3.jpg')}}" class="img-responsive"
							style="display: none;">
						</a>
						<a href="#" class="nivo-imageLink" style="display: none;">
							<img src="{{url_for('static',filename='image/slider2.jpg')}}" class="img-responsive"
							style="display: none;">
						</a>
					</div>
				</div>
				<div class="download f-pr">
					<span class="shadow"></span><span class="shadowr"></span>
				</div>
			</div>
			<div id="discover-module" class="g-bd1 f-cb">
				<div class="g-mn1">
					<div class="g-mn1c">
						<div class="g-wrap3">
							<div class="n-rcmd">
								<div class="v-hd2">
									<a href="#" class="tit f-ff2 f-tdn">热门歌手</a>
									<span class="more"><a href="{{url_for('home.artistList')}}"
										class="s-fc3">更多</a><i class="cor s-bg s-bg-6"> </i> </span>
								</div>
								<ul class="m-cvrlst f-cb">
									{% for artist in hot_artist %}
									<li>
										<div class="u-cover u-cover-1">
											<a href="{{url_for('home.artist',id=artist.id)}}">
												<img src="{{url_for('static',filename='images/artist/'+artist.imgURL)}}">
											</a>
										</div>
									</li>
									{% endfor %}
								</ul>
							</div>
						</div>
					</div>
				</div>
				<div class="g-sd1">
					<div class="n-dj n-dj-1">
						<h1 class="v-hd3">
							热门歌曲
						</h1>
						<ul class="n-hotdj f-cb" id="hotdj-list">
							{% for song in hot_song %}
							<li>
								<div class="info">
									<p>
										<a onclick='playA("{{song.songName}}","{{song.id}}");'
											style="color: #1096A9">{{song.songName}} </a>
										<sup class="u-icn u-icn-1"></sup>
									</p>
									<p class="f-thide s-fc3">
										歌手:{{song.singer}}
									</p>
								</div>
							</li>
							{% endfor %}
						</ul>
					</div>
				</div>
			</div>
<script>
//实现调用幻灯片插件轮播广告
jQuery(document).ready(function() {
	jQuery('#slidershow').nivoSlider();
});

function playA(name, id) {
	window.parent.playMusic(name,id);
}
</script>
</div>
</body>
</html>

效果图

启动服务器:

py -3.7 manager.py runserver

浏览器输入:

http://127.0.0.1:5000/home/contentFrame

可看到:


Python22020104.png

参考文档:

https://zhuanlan.zhihu.com/p/357444025