首页 > 解决方案 > 使用工作流在 github 中对 databricks python 代码进行 flake8 linting

问题描述

我有我的 databricks python 代码github。我设置了一个基本的工作流程来使用flake8. 这失败了,因为当它在 databricks 上运行时对我的脚本隐式可用的名称(如sparkscdbutilsgetArgument)在flake8databricks 外部(在 github ubuntu vm 中)进行 lints 时不可用。

如何在github使用中对 databricks 笔记本进行 lint flake8

例如我得到的错误:

test.py:1:1: F821 undefined name 'dbutils'
test.py:3:11: F821 undefined name 'getArgument'
test.py:5:1: F821 undefined name 'dbutils'
test.py:7:11: F821 undefined name 'spark'

我在 github 上的笔记本:

dbutils.widgets.text("my_jdbcurl", "default my_jdbcurl")

jdbcurl = getArgument("my_jdbcurl")

dbutils.fs.ls(".")

df_node = spark.read.format("jdbc")\
  .option("driver", "org.mariadb.jdbc.Driver")\
  .option("url", jdbcurl)\
  .option("dbtable", "my_table")\
  .option("user", "my_username")\
  .option("password", "my_pswd")\
  .load()

我的 .github/workflows/lint.yml

on:
  pull_request:
    branches: [ master ]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - uses: actions/setup-python@v1
      with:
        python-version: 3.8
    - run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    - name: Lint with flake8
      run: |
        pip install flake8
        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics

标签: pythonapache-sparkgithubdatabricksflake8

解决方案


您可以做的一件事是:

from pyspark.sql import Spark Session


spark = SparkSession.builder.getOrCreate()

这将在普通 Python 或pyspark客户端中使用或不使用 Databricks 工作。

要检测您是在文件中还是在 Databricks 笔记本中,您可以运行:

try:
    __file__
    print("We are in a file, like in our IDE or being tested by flake8.")
except NameError:
    print("We are in a Databricks notebook. Act accordingly.")

然后,您可以有条件地为display()和其他工具初始化或创建虚拟变量。

这只是部分解决方案。我正在研究一个更好的解决方案,我会不断更新这个答案。


推荐阅读