DEV Community

Mbaoma
Mbaoma

Posted on

SonarQube as a code health checker for Flask project

SonarQube is an open-source platform developed by SonarSource, which checks the quality of your code by running continuous checks for bug detection, code smells and security vulnerabilities. It supports over 20 programming languages.

We take the steps below, to run a health check on a Flask project:

Build the Flask project

  • Create and switch to a virtual environment
python3 -m venv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • Install requirements
pip3 install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode
  • Run the project
python3 main.py
Enter fullscreen mode Exit fullscreen mode

Install SonarQube

  • Install SonarQube using Docker
docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest
Enter fullscreen mode Exit fullscreen mode
  • Run SonarQube locally
http://localhost:9000/
Enter fullscreen mode Exit fullscreen mode

Default username and password is admin for both fields.

If asked to update password, kindly do so

image

Run an Analysis on SonarQube

  • We run an analysis manually, by clicking on the 'manually' option at the bottom of the page
    image

  • Fill the prompts and tell SonarQube to run your project locally
    image

  • Generate a token
    image

  • For our build, we select the 'Other' option, when asked what describes our build.
    We also have to download a scanner based on our operating system.
    image

  • We install SonarQube scanner following the prompts in this article.

wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.2.0.1873-linux.zip
unzip sonar-scanner-cli-4.2.0.1873-linux.zip
sudo mv sonar-scanner-4.2.0.1873-linux /opt/sonar-scanner
Enter fullscreen mode Exit fullscreen mode
  • Edit the sonar-scanner.properties file
Enter fullscreen mode Exit fullscreen mode

to contain

sonar.host.url=http://localhost:9000
sonar.sourceEncoding=UTF-8
Enter fullscreen mode Exit fullscreen mode
  • Create a file to automate the required environment variables configuration
sudo nano /etc/profile.d/sonar-scanner.sh
Enter fullscreen mode Exit fullscreen mode

to contain

#/bin/bash
export PATH="$PATH:/opt/sonar-scanner/bin"
Enter fullscreen mode Exit fullscreen mode
  • Add the sonar-scanner commands, to PATH variables
source /etc/profile.d/sonar-scanner.sh
Enter fullscreen mode Exit fullscreen mode
  • Verify that the PATH variable was changed as expected
env | grep PATH
Enter fullscreen mode Exit fullscreen mode

image

  • Verify SonarQube scanner was installed
sonar-scanner -v
Enter fullscreen mode Exit fullscreen mode

image

  • Next, run the command as marked in red ink in the picture below.

The command should be ran in the directory where you installed SonarQube

image

Expected result

image

SonarQube web page

image

Checkout my GitHub Repo to view my files.

Top comments (0)