Django构建RESTful网络服务:使用PostgreSQL替代SQLite

2022-09-2511:55:48后端程序开发Comments911 views字数 5571阅读模式

为什么要使用PostgreSQL?

  • 比SQLite更时髦(虽然我个人很喜欢SQLite,平时我个人的大部分存储需求它都能满足,关键是它还便携,可以随时拷贝走,我曾把花了19万买购的数据就放在SQLite里装在U盘里带来带去……不要学我);
  • 更像是在做开发,而不是在玩玩;
  • 项目最终是要上线的,不如从现在开始,就用PostgreSQL;
  • 好了,我理解为什么不用SQLite了,那为什么不用MySQL?——因为我的开发环境用的是WSL(Windows Subsystem of Linux),目前还装不了MySQL。

为什么要用WSL

  • 可以不用。
  • 但如果你没有试过WSL,可以尝试下。Windows10是最好的桌面系统(不接受反驳,用过Mac、不下十款的Linux桌面系统、微软家的其他系统,得出结论,Windows10是最好的桌面系统),所以建议在Windows10下完成能在Windows10完成的所有事。本项目中除了最后部署上服务器外,所有事都能在Windows下完成。
  • 最终部署的环境是Ubuntu环境,所以从现在开始,使用Ubuntu也不错。
  • WSL Ubuntu有Ubuntu的几乎所有功能(至少有几乎所有本项目能用上的功能),而且能跟“宿主”机有很好的互动。比如文件系统几乎是互通的,你可以在Ubuntu下访问Windows下的 文件,这一点是虚拟机比不上的。
  • WSL是一个应用,一旦环境被你弄毁了,大不了卸载重装,比重装一个物理机方便多了。

如何安装WSL文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html

不在本文所叙范围,请移移步必应。简单来说,先在启动功能中启用子系统功能,再到Windows商店中安装Ubuntu就好了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html

安装PostgreSQL

我在WSL Ubuntu中安装了PostgreSQL,也在一台Fedora23的机器上安装了PostgreSQL,过程大同小异。以下以Ubuntu为例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html

# 安装PostgreSQL
$ sudo apt update
$ sudo apt install postgresql postgresql-contrib

# 安装PostgreSQL后,它会为你的系统添加一个名为postgres的用户
# 创建PostgreSQL用户(角色)
# 以交互方式创建一个角色,我创建的是webdev,跟我的Linux用户同名。这个角色有超级权限。
$ sudo - i -u postgres createuser --interactive
(webdev)
# 创建一个角色同名数据库
$  sudo -i -u postgres createdb webdev
# 用webdev用户创建一个项目用的数据库
$ sudo -i -u webdev createdb django_rest
# 修改PostgreSQL用户密码
# 如果不能正常进行psql环境,可能是PostgreSQL服务没有启动,应当先启动服务。可以尝试使用sudo service postgresql start,不同环境中可以有差异。
$ sudo -u postgres psql
>>> alter user webdev with password '123456';
# 修改Ubuntu用户密码(如果需要的话)
$ sudo passwd -d postgres
$ sudo -u postgres passwd
# 重起PostgreSQL(如果须要)
# 如果不能正常重启,可以搜索相应解决办法
$ sudo service postgresql restart

Python操作PostgreSQL

# 安装新版的PostgreSQLPython驱动,旧版安装方法是pip install psycopg2
$ pip install psycopg2-binary
# 进入Python环境
$ python
>>>import psycopg2
# 建立连接。建立连接前请确保能正常进入psql环境。如果能进入环境,但不能用Python建立连接,请确保数据库名、角色名、密码配置无误
>>>conn = psycopg2.connect(database="django_rest", user="webdev", password="123456", host="127.0.0.1", port="5432")
# 新建游标
>>>cur = conn.cursor()
# 查询所有的表信息
>>>cur.execute('select * from pg_tables')
# 输出所有的表信息
>>>cur.fetchall()

在Django项目中修改数据库配置

# 在settings.py中,把 DATABASES修改为如下配置,库名、用户名、密码等按实际情况填写
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'django_rest',
        'USER': 'webdev',
        'PASSWORD': '5411',
        'HOST': '127.0.0.1',
        'PORT': '5432'
    }
}

新建一个应用,新建几个数据模型用以测试

在原来的Django项目中,新建一个名为mblog的应用(怎么新建应用?之前的文章已经写过,不再重复说明)。修改mblog/models.py如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html

"""
描述了一些数据模型,如用户信息、用户写的文章、用户对文章的评论、用户对评论的回复、用户的互粉关系。
虽然这个模型只是用来测试数据库连接的,但场景还是蛮真实的。
"""


from django.db import models


class BlogUsers(models.Model):
    """
    Blog users info
 """

    user_name = models.CharField(max_length=20)
    user_password = models.CharField(max_length=20)
    count_create_time = models.DateTimeField(auto_now_add=True)
    release_datetime = models.DateTimeField()


class BlogArticles(models.Model):
    # use the django.db.models.ForeignKey class to provide a many-to-one relationship
    #   many articles could belong to one user
    author = models.ForeignKey(
        BlogUsers,
        related_name='articles_author',
        # once the user is deleted all the articles that belong to this user to be
        #   deleted too
        on_delete=models.CASCADE  # on_delete 描述主表记录被删除后,对此条记录的操作,models.CASCADE表示跟随删除
    )    # 一个作者可以有多篇文章;当作者被注销了,文章也会被删除
    article_title = models.CharField(max_length=200)
    article_content = models.CharField(max_length=20000)
    create_datetime = models.DateTimeField(auto_now_add=True)
    release_datetime = models.DateTimeField()


class ArticleComments(models.Model):
    author = models.ForeignKey(
        BlogUsers,
        related_name='comments_author',
        on_delete=models.DO_NOTHING,
    )
    article = models.ForeignKey(
        BlogArticles,
        related_name='comments_article',
        on_delete=models.DO_NOTHING,  # models.DO_NOTHING表示主表记录删除后,对此条记录什么都不做
    )    # 当作者被注销了,评论还保留下来
    # 用parent_comment表示多级评论,‘sele’用以自我关联(即上级评论也是评论类,或者上上级评论也在同一个表中)
    parent_comment = models.ForeignKey('self', related_name='replied_comment', null=True, blank=True, on_delete=models.CASCADE)
    content = models.CharField(max_length=1000)


class SocialLink(models.Model):
    a_user = models.ForeignKey(
        BlogUsers,
        related_name='a_uer',
        on_delete=models.DO_NOTHING,
    )
    b_user = models.ForeignKey(
        BlogUsers,
        related_name='b_user',
        on_delete=models.DO_NOTHING,
    )
    is_fans = models.BooleanField(default=False)  # 表示a用户对b用户是否关注

Django数据迁移

$ python manage.py makemigrations mblog
$ python manage.py migrate

用DjangoModel向表中添加内容

$ python manage.py shell
>>> from mblog.models import BlogUsers, BlogArticles, ArticleComments, SocialLink,  CommentReply
>>> from datetime import datetime
>>> from django.utils import timezone


>>> datetime_ = timezone.make_aware(datetime.now(), timezone.get_current_timezone())


# 添加两个博客用户。
>>> dinglei = BlogUsers(user_name='丁磊', user_password='163good', release_datetime=datetime.now())
>>> huateng = BlogUsers(user_name='马化腾', user_password='qqgreat', release_datetime=datetime.now())
>>> dinglei.save()
>>> huateng.save()


# 丁磊与马化腾互粉
>>> SocialLink(a_user=dinglei, b_user=huateng, is_fans=True).save()
>>> SocialLink(a_user=huateng, b_user=dinglei, is_fans=True).save()


# 丁磊发表了一篇博文
>>> article = BlogArticles(author=dinglei, article_title='网易游戏真好玩', article_content='不氪金你怎么能变强,氪金也不一定变强', release_datetime=datetime_)
>>> article.save()


# 马化腾评论了文章
>>> comment = ArticleComments(author=huateng, article=article, content='我有王者荣耀')
>>> comment.save()
>>>
>>> dinglei_reply = ArticleComments(author=dinglei, article=article, parent_comment=huateng_comment, content='倩女幽魂,国民手游啊')
>>> dinglei_reply.save()
>>>
>>> huateng_reply = ArticleComments(author=huateng, article=article, parent_comment=dinglei_reply, content='我有王者荣耀')
>>> huateng_reply.save()
>>>
>>> dinglei_reply = ArticleComments(author=dinglei, article=article, parent_comment=huateng_reply, content='阴阳师 平安京,和风moba你有吗?')
>>> dinglei_reply.save()
>>>
>>> huateng_reply = ArticleComments(author=huateng, article=article, parent_comment=dinglei_reply, content='我有王者荣耀')
>>> huateng_reply.save()
>>>
>>> dinglei_reply = ArticleComments(author=dinglei, article=article, parent_comment=huateng_reply, content='我。。。')
>>> dinglei_reply.save()
>>>
>>> huateng_reply = ArticleComments(author=huateng, article=article, parent_comment=dinglei_reply, content='我有王者荣耀')
>>> huateng_reply.save()

最后,可以用图形化界面查看数据库中的数据文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html

Django构建RESTful网络服务:使用PostgreSQL替代SQLite
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28058.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/28058.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定