Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ venv*/

# VS Code IDE
/.vscode/
*.code-workspace
<<<<<<< HEAD
*.code-workspace
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,18 @@
# File server project

Author is Vasyl Pidhirskyi.

## Сделанные требования

Get port and working directory via arguments
Work independently without WSGI
Suit with RESTful API requirements
Provide sharing access to files and access policy
Protect files by cryptography tools
Use asynchronous programming concept
Work with database
Use multithreading for downloading files

## Желаемые требования

TODO: заполните требования
31 changes: 31 additions & 0 deletions demo/docstrings/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""This is demo module.

It contains a lof useful functions.
Here you can find a class `MyClass`.
"""


class MyClass:
@staticmethod
def sum(a: int, b: int) -> int:
"""Sum the values of two numbers.

Args:
a (int): number 1
b (int): number 2

Returns:
This is a description of what is returned.

Raises:
KeyError: Raises an exception.
"""
return a + b


print(dir(MyClass.sum))
print("__annotations__:", MyClass.sum.__annotations__)
print("__doc__:", MyClass.sum.__doc__)
print("call:", MyClass.sum(1, 2))
print("call:", MyClass.sum("bug", "bug"))
print("call:", MyClass.sum(1, "bug"))
16 changes: 16 additions & 0 deletions demo/docstrings/docstring.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

# Documentation

https://www.python.org/dev/peps/pep-0257/
https://docs.python-guide.org/writing/documentation/


# Different styles

https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format


#

- VS Code extension njpwerner.autodocstring
- PyCharm settings
11 changes: 11 additions & 0 deletions demo/exceptions/demo1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def summa(n1, n2):
if type(n1) != 'int':
# TODO: show stack trace
raise TypeError('incorrect type: {}'.format(type(n1)))
return n1 - n2


try:
summa('a', 'b')
except (TypeError, RuntimeError) as e:
print("error occurred {}".format(e.message))
11 changes: 11 additions & 0 deletions demo/exceptions/exc_add_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
try:
with open(path, "r") as f:
return dict(name=f.name,
content=f.read(),
create_date=time.strftime('%d.%M.%Y %H:%M:%S', time.gmtime(os.path.getctime(path))),
edit_date=time.strftime('%d.%M.%Y %H:%M:%S', time.gmtime(os.path.getmtime(path))),
size=int(os.path.getsize(path)))
except RuntimeError as err:
e.args += ('Custom message',)
...

6 changes: 6 additions & 0 deletions demo/exceptions/exception_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
if __name__ == '__main__':
try:
main()
except BaseException as err:
# logging
print("всё плохо {}".format(err))
6 changes: 6 additions & 0 deletions demo/exceptions/try-except.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
try:
d = int(input('>'))
x = 2 / d
print(x)
except Exception as e:
print(e)
Empty file.
11 changes: 11 additions & 0 deletions demo/modules/example1/mod1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# import mymodules.mod2

name = 'Me'


def whoami():
print(name)


print("mod1: {}".format(__name__))
started = True
Empty file.
3 changes: 3 additions & 0 deletions demo/modules/example1/mymodules/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import mod2

print('mymodules started')
5 changes: 5 additions & 0 deletions demo/modules/example1/mymodules/mod2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def hello():
print("Hello, world")


print("mod2: {}".format(__name__))
3 changes: 3 additions & 0 deletions demo/modules/example2/changer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import config

config.globalvar = '0'
2 changes: 2 additions & 0 deletions demo/modules/example2/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

globalvar = 'default'
28 changes: 28 additions & 0 deletions demo/modules/example2/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import config
import changer
import config as baseConfig
from config import globalvar as g # separate variable --> it's a copy, so changes don't affect it

print('--- step 0 ---')
print(f'config.globalvar: {config.globalvar}')
print(f'baseConfig.globalvar: {baseConfig.globalvar}')
print(f'g: {g}')

print('--- step 1 ---')
config.globalvar = '1'
print(f'config.globalvar: {config.globalvar}')
print(f'baseConfig.globalvar: {baseConfig.globalvar}')
print(f'g: {g}')

print('--- step 2 ---')
baseConfig.globalvar = '2'
print(f'config.globalvar: {config.globalvar}')
print(f'baseConfig.globalvar: {baseConfig.globalvar}')
print(f'g: {g}')


print('--- step 3 ---')
g = '3'
print(f'config.globalvar: {config.globalvar}')
print(f'baseConfig.globalvar: {baseConfig.globalvar}')
print(f'g: {g}')
5 changes: 5 additions & 0 deletions demo/modules/example3/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import mypackage

mypackage.init_function()
mypackage.mymodule.myfunction()
mypackage.f13()
9 changes: 9 additions & 0 deletions demo/modules/example3/mypackage/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

# other good examples:
# https://github.com/pallets/flask/blob/main/src/flask/__init__.py

from . import mymodule
from .mymodule import myfunction as f13

def init_function():
return True
3 changes: 3 additions & 0 deletions demo/modules/example3/mypackage/mymodule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

def myfunction():
return 13
65 changes: 65 additions & 0 deletions demo/ospath/ospath.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@

# Работа с файловой системой

Широко используются два модуля `os` и `os.path`.

## Модуль `os`

[Документация `os`](https://docs.python.org/3/library/os.html)

Модуль используется для работы с файлами на диске:

os.chdir(path) - установить текущий каталог
os.getcwd() - получить текущий каталог
os.listdir(path='.') - получить список файлов в каталоге

os.makedirs(name, mode=0o777, exist_ok=False) - создать папку (с вложенными папками)
os.mkdir(path, mode=0o777) - создать папку (родительские папки должны быть уже созданы)

os.remove(path) - удалить файл
os.rmdir(path) - удалить пустую папку
os.removedirs(name) - удалить непустую папку

Есть также функции по переименования, переносу файлов и другие.

## Модуль `os.path`

[Документация `os.path`](https://docs.python.org/3/library/os.path.html)

Используется для работы с файловым путём:

os.path.dirname(path) - получить имя родительской папки

```python
>>> os.path.dirname('c:\\1\\2\\3.txt')
'c:\\1\\2'
```

os.path.join(path, *paths) - соединить несколько папок в один путь

```python
>>> os.path.join(os.getcwd(), 'data')
'C:\\Work\\TC\\Trainings\\My\\python\\script-007\\demo\\argparsing\\data'

>>> os.path.join(os.getcwd(), 'data', 'testfiles')
'C:\\Work\\TC\\Trainings\\My\\python\\script-007\\demo\\argparsing\\data\\testfiles'
```

os.path.lexists(path) - проверить, что файл или папка существует

```python
>>> os.path.exists('c:\\1')
False

>>> os.path.exists('c:\\')
True
```

os.path.is*(path) - проверить что объект является контретным типом

os.path.islink(path)
os.path.isdir(path)
os.path.isfile(path)


os.path.getsize(path) - получить размер файла
Empty file added demo/tests/__init__.py
Empty file.
17 changes: 17 additions & 0 deletions demo/tests/myfuncs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import os


def myadd(a, b):
if a > 100:
return 100
return a + b


def tricky_func():
a = 1
b = a + 1
return b


def checkfile(filename):
return os.path.isfile(filename)
4 changes: 4 additions & 0 deletions demo/tests/mypytests/.coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[run]
omit = tests/mypytests/*
tests/myunittests/*
tests/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions demo/tests/mypytests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import os

import pytest


@pytest.fixture(scope='function')
def prepare_testfile(request):
print('prepare_testfile: before test')
with open('testfile.txt', 'w') as f:
f.write('first line')

yield # Run tests

print('prepare_testfile: after test')
if os.path.exists('testfile.txt'):
os.remove('testfile.txt')
Loading