使用JupyterLab进行数据分析

使用 Jupyter Lab 并访问PostgreSQL数据库,并组合使用SQL与Python的能力进行数据分析。

Jupyter Lab 是基于 IPython Notebook 的完整数据科学研发环境,可用于数据分析与可视化。

因为JupyterLab提供了Web Terminal功能,因此在默认安装中不启用,需要主动使用 infra-jupyter.yml 在元节点上进行部署。

太长不看

./infra-jupyter.yml # 在管理节点上安装 Jupyter Lab,使用8888端口,OS用户jupyter,默认密码 pigsty
./infra-jupyter.yml -e jupyter_domain=lab.pigsty.cc  # 使用另一个域名(默认为lab.pigsty)
./infra-jupyter.yml -e jupyter_port=8887             # 使用另一个端口(默认为8888)
./infra-jupyter.yml -e jupyter_username=osuser_jupyter jupyter_password=pigsty2 # 使用不同的操作系统用户与密码

Jupyter配置

Name Type Level Comment
jupyter_port integer G Jupyter端口
jupyter_domain string G Jupyter端口
jupyter_username string G Jupyter使用的操作系统用户
jupyter_password string G Jupyter Lab的密码

默认值

jupyter_username: jupyter       # os user name, special names: default|root (dangerous!)
jupyter_password: pigsty        # default password for jupyter lab (important!)
jupyter_port: 8888              # default port for jupyter lab
jupyter_domain: lab.pigsty      # domain name used to distinguish jupyter

jupyter_username

Jupyter使用的操作系统用户, 类型:bool,层级:G,默认值为:"jupyter"

其他用户名亦同理,但特殊用户名default会使用当前执行安装的用户(通常为管理员)运行 Jupyter Lab,这会更方便,但也更危险。

jupyter_password

Jupyter Lab的密码, 类型:bool,层级:G,默认值为:"pigsty"

如果启用Jupyter,强烈建议修改此密码。加盐混淆的密码默认会写入~jupyter/.jupyter/jupyter_server_config.json

jupyter_port

Jupyter监听端口, 类型:int,层级:G,默认值为:8888

启用JupyterLab时,Pigsty会使用jupyter_username 参数指定的用户运行本地Notebook服务器。 此外,需要确保配置node_packages_meta_pip 参数包含默认值 'jupyterlab'。 Jupyter Lab可以从Pigsty首页导航进入,或通过默认域名 lab.pigsty 访问,默认监听于8888端口。

jupyter_domain

Jupyter域名, 类型:string,层级:G,默认值为:lab.pigsty

该域名会被写入 /etc/nginx/conf.d/jupyter.conf 中,作为Jupyter服务的监听域名。


Jupyter剧本

infra-jupyter

infra-jupyter.yml 剧本用于在元节点上加装 Jupyter Lab服务

Jupyter Lab 是非常实用的Python数据分析环境,但自带Web Shell,风险较大,需要使用专用剧本显式安装。

使用说明:参照 Jupyter配置 中的说明调整配置清单,然后执行此剧本即可。

如果您在生产环境中启用了Jupyter,请务必修改Jupyter的密码


在Jupyter中访问PostgreSQL数据库

您可以直接使用 psycopg2 驱动访问 PostgreSQL 数据库

import psycopg2
conn = psycopg2.connect('postgres://dbuser_meta:DBUser.Meta@:5432/meta')
cursor = conn.cursor()
cursor.execute("""SELECT date, new_cases FROM covid.country_history WHERE country_code = 'CN';""")
data = cursor.fetchall()

Last modified 2024-02-29: update content (34b2b75)