diff --git a/apps/codesamples/factories.py b/apps/codesamples/factories.py index 654364d7a..d770cccea 100644 --- a/apps/codesamples/factories.py +++ b/apps/codesamples/factories.py @@ -4,6 +4,9 @@ import factory from factory.django import DjangoModelFactory +from pygments import highlight +from pygments.formatters import HtmlFormatter +from pygments.lexers import PythonConsoleLexer from apps.codesamples.models import CodeSample from apps.users.factories import UserFactory @@ -26,22 +29,28 @@ class Meta: is_published = True +def _highlight_python_console(code): + """Highlight a Python console code snippet using Pygments.""" + code = textwrap.dedent(code).strip() + html = highlight(code, PythonConsoleLexer(), HtmlFormatter(nowrap=True)) + return f"
{html}"
+
+
def initial_data():
"""Create the default set of homepage code samples."""
code_samples = [
(
- """\
- # Simple output (with Unicode)
+ """
+ # Simple output (with Unicode)
>>> print("Hello, I'm Python!")
- Hello, I'm Python!
+ Hello, I'm Python!
- # Input, assignment
- >>> name = input('What is your name?\n')
- What is your name?
- Python
+ # Input, assignment
+ >>> name = input('What is your name?\\n')
>>> print(f'Hi, {name}.')
- Hi, Python.
-
+ What is your name?
+ Python
+ Hi, Python.
""",
"""\
# Simple arithmetic
+ """
+ # Simple arithmetic
>>> 1 / 2
- 0.5
+ 0.5
>>> 2 ** 3
- 8
- >>> 17 / 3 # true division returns a float
- 5.666666666666667
- >>> 17 // 3 # floor division
- 5
+ 8
+ >>> 17 / 3 # true division returns a float
+ 5.666666666666667
+ >>> 17 // 3 # floor division
+ 5
""",
"""\
# List comprehensions
+ """
+ # List comprehensions
>>> fruits = ['Banana', 'Apple', 'Lime']
>>> loud_fruits = [fruit.upper() for fruit in fruits]
>>> print(loud_fruits)
- ['BANANA', 'APPLE', 'LIME']
+ ['BANANA', 'APPLE', 'LIME']
- # List and the enumerate function
+ # List and the enumerate function
>>> list(enumerate(fruits))
- [(0, 'Banana'), (1, 'Apple'), (2, 'Lime')]
+ [(0, 'Banana'), (1, 'Apple'), (2, 'Lime')]
""",
"""\
-
- # For loop on a list
+ """
+ # For loop on a list
>>> numbers = [2, 4, 6, 8]
>>> product = 1
>>> for number in numbers:
... product = product * number
...
>>> print('The product is:', product)
- The product is: 384
-
-
+ The product is: 384
""",
"""\
-
- # Write Fibonacci series up to n
+ """
+ # Write Fibonacci series up to n
>>> def fib(n):
... a, b = 0, 1
- ... while a < n:
+ ... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> fib(1000)
- 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
-
-
+ 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
""",
"""\