Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt

Real Python · Intermediate ·🛠️ AI Tools & Apps ·9y ago

Key Takeaways

This video tutorial covers a Python code review for a Flask web security project, emphasizing the importance of virtual environments, proper dependency management, and secure coding practices using tools like Flask, pipenv, and Jinja.

Full Transcript

hey everyone so it's time for another code review unplugged episode and today I'm going to look at some code that Carl has sent me so this is actually a really cool project because it's um yeah it is a security a tutorial for fixing and I well identifying and fixing security vulnerabilities in a tiny flask web app and I like this it's not a lot of code so you know should be relatively easy for for people to go through this but I kind of like you know the short and sweet description here and I like the fact that that it's trying to teach people something with code and actually making them do something so I think this would be great for a little workshop or I don't really know where it is where this comes from if this if Carl you know if you were doing this at at a company or some kind of public workshop but I really like the idea and it should definitely keep going like I think it's a really really cool way to teach people so yeah so all I did so far was pull this up in github and then also just clone the repo locally let's also open that up in sublime text maybe crank down the font size a bit and yeah cool so so what I really like here is that the readme is pretty extensive and you know just kind of contains all you need I am not a hundred percent clear what version of Python we're dealing with like just looking at the requirements txt file it's great that we have a requirements txt file by the way this is using the flask module and a bunch of other stuff and it looks like we're supposed to just install this globally so with this like I typically I wouldn't recommend installing these things globally unless it's like a tool like a lint or something you need all the time so usually I would not install new Python libraries modules with pseudo pip install like what I would do I'm just going to assume this is Python 3 and we'll see what happens like I would create a new virtual environment with the PI vnf command and then I'm going to activate that this other command and I actually have a shortcut here in my shell setup so I can just do de to deactivate a vnf in AE to activate one maybe should crank up the font size a bit too so I was just saying like I can do de then AE to activate and deactivate these VMs and like a virtual end is essentially a local copy of your Python environment so that when you install new modules they don't gum up your global Python install but they're localized to just this folder so like we can look into this with LS and you know you can see that here we actually have a tiny well almost like a tiny Python install here right like with a bin folder and a library folder and all of that so look into Python virtual ends and then if because this is a tutorial for for newbies like I would potentially consider you know teaching them about virtual ends because in the long run they're probably not going to be happy installing these requirements into their global Python install so I'm going to do here um just install the requirements great that you have in a requirements file here always always great because it just makes setting up this stuff a lot easier and you've pinned your requirements to to fix versions that's great too ok so now I guess I'm yeah probably not going to play through the whole tutorial but I want to make sure I can run the tests and kind of also maybe spin up the app so it can make sure it's running okay so let's go Python app not pi okay cool looks like it's running nice I like the green sweet soups work Strahm OG works - excellent no unicode errors no I'm cool so it looks like this is running let's try let's try and make sure we get the test running as well so that's usually what I try to do with in with a new project just to make sure I can run the tests as well so okay so it looks like there's no instructions on how to run the tests so maybe with the way we can figure that out is we'll just look at the tests and then yeah we can see it's a script file or it it does dislike imports unit tests and just cause unit tests main so it looks like we can just run this like a regular Python script and in tests pass cool so it looks like we've got this running so why don't we take a look at the code now and I'm going to do this in sublime texts I think it's going to be a better environment to do that in okay like I said the requirements look good let's look at app dot pi okay so this is like a tiny flask app yeah we have got this global posts here I mean I think for an example like that that's totally fine that we're not doing any kind of persistence so I'm not going to focus on that okay so maybe the first thing that actually catches my eye is that these comments here they could be docstrings so just to show you what a doc string is it's like when you do these three like typically the convention would be it could be any old string as long as like the first thing that happens in your in your function but like typically you would format them like this and then this would be the doc string and the cool thing about dark strings is that they're treated a little bit special by the Python Python parser or the Python runtime because these doc strings are actually accessible you know through from from within the program and that means there are a lot of tools around that allow you to generate documentation based on these stock strings and so it's just like good practice to you know not have these kind of inline comments for dark strings just kind of use proper doc strings just because I'm seeing that here everywhere like you're really just describing the function I think that's that's great and that's the right way to go about it but you probably want to put that information into a dark string and not just into a an inline comment so that's probably what I would change I'm here with the output I mean I think I think that's fine too because you just you know you want to do this like minimum minimal example here obviously like for a larger app or whatever like this would be loaded from from some kind of template file and probably be handled through a proper templating system also to avoid stuff like this where we're just concatenate and I know you know this is part of the the challenge here's I don't want to spoil app for people but like you know you could really easily like inject all kinds of stuff like inject script tack or do something else like that and there's no like validation for that but that's part of the the game like it's part of the whole tutorial right so that's I really like that well done yeah in terms of you know how you're formatting this small app like I think it looks good like it's it's nice to read it's like formative consistently honestly the only thing I really saw was the the dark strings here um so yeah I can't really complain about that and then for the unit tests I think this works well too you know again like in terms of the the formatting like maybe one tiny thing like I'm seeing that you've switched your quote types you know you're using double quotes down here and in single quotes there but that's something that that personally like I I would I would change that for consistency but I mean in the grand scheme of things it's not a big deal and what like one way you can you can deal with that is just by having syntax highlighting that actually highlights them differently I mean if you wanna if you want to go for consistency right then then you would need that if you don't want to then it doesn't really matter but anyway okay so probably change that in terms of how the tests or what the tests look like I think that makes sense to based on what you're doing I don't think it makes sense to pull in like you know something like web test which is like a bigger framework for testing these kinds of web apps which you know it really helps when you're working on a larger project but like for what you're doing with this tutorial I think it is great that you're keeping the dependencies simple and just kind of focused on well basically flask right so actually with this stuff what I would probably do here in terms of the dependencies I would probably just put in flask as a dependency and then it's not really necessary to like spec out all these other ones because then it becomes really clear what the real dependencies are because all of this other stuff is presumably getting pulled in by flask like Jinja that's the templating thing and all that stuff and works like it's like the underlying libraries that flask is built on top off but on the other hand if you do you you know if you do like a pip freeze then then that's like the classical way to freeze your dependency so you know because this is a tutorial I I might think about like just having flasks there so that people who are looking at it they can realize like oh you know all we're really using here is flask which I might be like a valuable well I want to say lesson but like a valuable piece of information for people but like honestly like you know this is super nitpicky what I'm what I'm saying there yeah I got some CSS there yeah it's pretty self-contained I mean arguably we could also serve the CSS in line here but yeah that doesn't that doesn't really matter matter we've got a good ignore which i think is great it's gonna you know it's going to make sure that people who submit pull requests and stuff for for your your app here are not gonna hopefully not going to commit like all kinds of crazy files that you didn't have to sort out yeah I think this is pretty cool like honestly like there's not a lot of stuff I could I could find here and I really liked the tutorial so anyone who's watching this like try and play through the door tutorial I think it'll probably teach you some some valuable things about avoiding some of these vulnerabilities like I'm hoping there's some kind of solution sheep for that I think would be great if that was there because I really liked the idea behind this tutorial and yeah like I think we're we're ready to wrap this up please write a longer blog post about the tutorial I think it's a really good idea cool thanks Carl and good luck

Original Description

https://dbader.org/python-tricks ► Write more Pythonic code with hands-on code examples Python Code Review: Unplugged – Episode 4: Code Review for Karl This is a Python code review I did for Karl's web security tutorial available here on GitHub: • https://github.com/agentreno/aas-demo • https://agentreno.github.io/2016/10/22/a-basic-course-in-web-application-security.html This is a shorter episode in which I talk about Python virtualenvs and requirements.txt handling among other things. As with the other videos in this series, I left the video completely unedited. That’s why I’m calling this series Code Review: Unplugged. It’s definitely not a polished tutorial or course. But based on the feedback I got so far that seems to be part of the appeal. FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube * * * ► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com FREE Python Tutorials & News: » Python Tutorials: https://dbader.org » Python News on Twitter: https://twitter.com/@dbader_org » Weekly Tips for Pythonistas: https://dbader.org/newsletter » Subscribe to this channel: https://dbader.org/youtube
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 25 of 60

1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches viewers how to conduct a Python code review for a Flask web security project, focusing on virtual environments, dependency management, and secure coding practices. Viewers will learn how to use tools like Flask, pipenv, and Jinja to develop secure web applications.

Key Takeaways
  1. Create a new virtual environment with pipenv
  2. Activate the virtual environment with deactivate and activate commands
  3. Install requirements from requirements.txt file
  4. Run the Flask app with python app.py
  5. Run tests as a regular Python script
  6. Format code for consistency
  7. Use docstrings for function comments
💡 Using virtual environments and managing dependencies properly is crucial for secure and efficient web development with Flask.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →