欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django项目案例之GitHub用户接口展示

程序员文章站 2022-06-19 15:42:48
Django 项目mysite在Terminal终端中运行命令python manage.py migrate(base) D:\PyCharm WorkSpace\mysite>python manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, sessionsRunning migrations: Applying contenttypes.0001_ini...

项目最终展示

Django项目案例之GitHub用户接口展示
可以在搜素框中输入你想搜的用户名进行搜索;也可以直接点击访问进行页面跳转;

下面记录一下该项目的学习过程:

  • Pycharm下创建Django项目,项目名称为mysite

  • 首先在Terminal终端中运行命令python manage.py migrate

(base) D:\PyCharm WorkSpace\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

  • 接着启动服务python manage.py runserver
(base) D:\PyCharm WorkSpace\mysite>python manage.py runserver

Django项目案例之GitHub用户接口展示

  • mysite作为主体,创建新的apppython manage.py startapp show,app的名称为show
(base) D:\PyCharm WorkSpace\mysite>python manage.py startapp show
  • 在mysite->settings中关联新创建的show
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'show',
]
  • 配置路由urls
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('show.urls'))
]

admin是Django自带的管理页面,本项目并未涉及;加入include模块,不用将所有的url配置都放在mysite中,''表示根目录的意思,即http://127.0.0.1:8000/

  • 接下来要在show的框架中新建urls.py文件
from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name='home'),
    path('user/', views.user, name='user')
]

代码from . import views表示引用同一目录下的views.py文件path('', views.home, name='home')中的name属性可以在html文件中进行调用,如href="{% url 'home' %}views.home是views.py文件中定义的home函数

  • views.py 文件中的内容如下
from django.shortcuts import render
import requests
import json

def home(request):

    api_request = requests.get('https://api.github.com/users?since=0')
    api = json.loads(api_request.content)

    return render(request, 'home.html', {'api': api})

def user(request):
    # 获取搜索框中输入的内容,前端搜索框文本的名称为input_content
    user_name = request.POST['input_content']
    if user_name:  # 输入内容不为空
        # 同home函数中获取api接口内容
        user_request = requests.get(url='https://api.github.com/users/' + user_name)
        user_info = json.loads(user_request.content)
        # 返回函数包含两个数据,分别是要搜索的用户名和对应的用户信息
        return render(request, 'user.html', {'input_contents': user_name, 'user_info': user_info})
    else:
        # 若搜索框内没有输入,则进行提示
        notfound = '请在搜索框中输入您需要查询的用户...'
        return render(request, 'user.html', {'notfound': notfound})

如果requests模块未安装,可以使用pip命令pip install requests安装;
这里是调用GitHub中的接口,来获取GitHub的所有用户信息,接口具体内容可以参考网址 github-APIhttps://api.github.com/users?since=0,since=0表示id从第一个用户开始,这里的api网址也可以不加?since=0,同样可以获得所有的用户信息;项目中用到的属性有login(用户名)、avatar_url(用户头像)、html_url(用户github个人首页);url='https://api.github.com/users/'+user_name这里是查询具体用户信息的api接口,可以自行探索;
views.py中自定义函数中默认参数为request,返回render(request, 'home.html', {'api': api}),home.html表示url要跳转的前端页面,{‘key’:value}中的value是返回的数据,在html页面中使用{{ key }}来获取数据value;

  • 在show的框架中新建templates文件夹,里面新建home.html,base.html,user.html,前端使用BootStrap框架,参考BootStrap4中文文档的模板,使用的模板有快速入门中的最基本的模板
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>

组件中的导航条(Navbar)模板
Django项目案例之GitHub用户接口展示

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

组件中的卡片(Card)模板
Django项目案例之GitHub用户接口展示

<div class="card" style="width: 18rem;">
  <img src="..." class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">Card title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

组件中的巨幕(Jumbotron)模板

<div class="jumbotron jumbotron-fluid">
  <div class="container">
    <h1 class="display-4">Fluid jumbotron</h1>
    <p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
  </div>
</div>
  • base.html定义项目的前端基础页面,使用了Bootstrap的模板,同时使用block模块来展示home.html与user.html中的内容,因此home.html与user.html都使用命令{% extends 'base.html' %}继承base.html,使得代码解耦,base.html的内容如下(在搜索框相关部分加入{% csrf_token %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>Show</title>
  </head>

  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="{% url 'home' %}">主页</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
{#                <li class="nav-item">#}
{#                    <a class="nav-link" href="{% url 'user' %}">查询</a>#}
{#                </li>#}
            </ul>

            <form class="form-inline my-2 my-lg-0" method="post" action="{% url 'user' %}">
                {% csrf_token %}
                <input class="form-control mr-sm-2" name="input_content" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
            </form>
        </div>
    </nav>

    <div class="container">
        {% block content %}
        {% endblock %}
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>
  • home.html接收views.py中home函数传到前端的数据,数据名为api,使用for循环来遍历api数据,前端使用for循环代码格式如下
{% for x in api %}
{% endfor %}

home.html具体内容如下

{% extends 'base.html' %}
{% block content %}
    <div class="jumbotron jumbotron-fluid">
      <div class="container">
        <h1 class="display-4">Django案例之GitHub用户接口展示</h1>
          <p class="lead">教程参考 <a href="https://www.bilibili.com/video/BV1KJ41117HL" >https://www.bilibili.com/video/BV1KJ41117HL</a></p>
      </div>
    </div>
    <div class="container">
        <div class="row">
            {% for x in api %}
            <div class="col-sm-4">
                <div class="card" style="width: 18rem;">
                    <img src="{{x.avatar_url}}" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">{{ x.login }}</h5>
                        <p class="card-text">{{ x.login }}的GitHub</p>
                        <a href="{{ x.html_url }}" class="btn btn-primary">访问</a>
                    </div>
                </div>
                <br>
            </div>
            {% endfor %}
        </div>
    </div>
{% endblock %}
  • user.html中涉及搜索框(在搜索框中输入用户名即可),因此要判断前端搜索框(input_content)是否为空,不为空则返回要搜索的具体用户相关信息,代码如下
{% extends 'base.html' %}
{% block content %}
    {% if notfound %}
        <h2>{{ notfound }}</h2>
    {% else %}
        <h1>Hello {{ input_contents }}</h1>
        <div class="card" style="width: 18rem;">
            <img src="{{user_info.avatar_url}}" class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">{{ user_info.name }}</h5>
                    <p class="card-text">company: {{ user_info.company }}</p>
                    <p class="card-text">blog: {{ user_info.blog }}</p>
                    <p class="card-text">location: {{ user_info.location }}</p>
                </div>
        </div>
    {% endif %}
{% endblock %}
  • 最终系统框架如下图
    Django项目案例之GitHub用户接口展示

现在就可以直接运行项目了,在Terminal命令行中使用命令python manage.py runserver或者直接在Pycharm中运行项目mysite,因为调用的是GitHub的接口,所以图片加载会慢一些;

总结:Django项目开发(未涉及到数据库相关)的流程大体就是,首先是功能拆分(创建不同的app),然后配置路由,在views.py中向前端html页面传递数据,前端使用相关的Bootstrap模板进行数据展示;

所有代码均已上传至GitHub项目地址

感谢哔哩哔哩上的教学视频,链接分享在此:哔哩哔哩学习

本文地址:https://blog.csdn.net/weixin_43108122/article/details/109217858