Skip to content

Instantly share code, notes, and snippets.

@vitalizzare
Created December 27, 2020 01:24
Show Gist options
  • Save vitalizzare/193bbe017230e24d23f42ba84f8ac589 to your computer and use it in GitHub Desktop.
Save vitalizzare/193bbe017230e24d23f42ba84f8ac589 to your computer and use it in GitHub Desktop.
Split module into multiple files
from .social_media_post import SocialMediaPost
from .social_media_post_publisher import SocialMediaPostPublisher
# This is used by 'from socsocial_media_post import *'
# As far as there is nothing else here and in app.py
# we import the classes explicitely, this part can be ommited
__all__ = [
'SocialMediaPost',
'SocialMediaPostPublisher'
]
from social_media_post import (
SocialMediaPost,
SocialMediaPostPublisher,
)
post = SocialMediaPost('Hey guys!')
# NOTE: here SocialMediaPostPublisher is identified by media, not by post
publisher = SocialMediaPostPublisher(['Facebook', 'Twitter'])
publisher.publish(post)
class Facebook:
# See notes for Twitter
def publish(self, post):
print(f'Publish on Facebook via its API: {post.content}')
class LinkedIn:
# See notes for Twitter
def publish(self, post):
print(f'Publish on Linkedin via its API: {post.content}')
''' NOTE: gist.github.com does not allow directory creation.
Helper to make a social_media_post directory and move there files,
derived from social_media_post.py
'''
from pathlib import Path
module_folder = Path('social_media_post')
module_folder.mkdir()
files = [
'__init__.py',
'twitter.py',
'facebook.py',
'linkedin.py',
'social_media_post_publisher.py',
'social_media_post.py',
]
files = [Path(file) for file in files]
for file in files:
file.replace(module_folder/file)
class SocialMediaPost:
def __init__(self, content):
self.content = content
# We import media locally, so we can reduce social_media_post.media to .media
from .twitter import Twitter
from .facebook import Facebook
from .linkedin import LinkedIn
PLATFORMS = {
'Twitter': Twitter(),
'Facebook': Facebook(),
'LinkedIn': LinkedIn()
}
class SocialMediaPostPublisher:
def __init__(self, platforms):
# The publisher is defined by the media, it has access to, not by a post
if any(name not in PLATFORMS for name in platforms):
raise Exception(f'Not all provided platforms are supported.')
self.platforms = platforms
def publish(self, post):
for name in self.platforms:
PLATFORMS[name].publish(post)
class Twitter:
# NOTE: see for the opportunity to use a metaclass to force derived classes
# explicitly declare the publish method
def publish(self, post):
# TODO: replace 'Twitter' with self.__class__.__name__
print(f'Publish on Twitter via its API: {post.content}')
@vitalizzare
Copy link
Author

vitalizzare commented Dec 27, 2020

  1. download
  2. unzip
  3. run python make_project_structure.py
  4. run python app.py

See code on github
See original tweet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment