aiofox 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. aiofox/VERSION +1 -0
  2. aiofox/__init__.py +12 -0
  3. aiofox/__main__.py +7 -0
  4. aiofox/cmdline.py +178 -0
  5. aiofox/commands/__init__.py +197 -0
  6. aiofox/commands/crawl.py +40 -0
  7. aiofox/commands/genspider.py +174 -0
  8. aiofox/commands/list.py +34 -0
  9. aiofox/commands/new.py +9 -0
  10. aiofox/commands/onespider.py +33 -0
  11. aiofox/commands/run.py +85 -0
  12. aiofox/commands/runspider.py +82 -0
  13. aiofox/commands/shell.py +312 -0
  14. aiofox/commands/startproject.py +132 -0
  15. aiofox/commands/version.py +36 -0
  16. aiofox/core/__init__.py +0 -0
  17. aiofox/core/downloader/__init__.py +294 -0
  18. aiofox/core/downloader/browser_pool.py +356 -0
  19. aiofox/core/downloader/handlers/__init__.py +0 -0
  20. aiofox/core/downloader/handlers/_errors.py +67 -0
  21. aiofox/core/downloader/handlers/aiohttp.py +121 -0
  22. aiofox/core/downloader/handlers/curl_cffi.py +100 -0
  23. aiofox/core/downloader/handlers/httpx.py +101 -0
  24. aiofox/core/downloader/handlers/playwright.py +344 -0
  25. aiofox/core/downloader/handlers/pyhttpx.py +72 -0
  26. aiofox/core/downloader/handlers/requests.py +83 -0
  27. aiofox/core/downloader/playwright_actions.py +129 -0
  28. aiofox/core/engine.py +418 -0
  29. aiofox/core/scheduler/__init__.py +158 -0
  30. aiofox/core/scheduler/memory.py +113 -0
  31. aiofox/core/scheduler/redis.py +106 -0
  32. aiofox/core/scraper.py +301 -0
  33. aiofox/crawler.py +249 -0
  34. aiofox/dupefilters.py +218 -0
  35. aiofox/exceptions.py +124 -0
  36. aiofox/exporters.py +95 -0
  37. aiofox/http/__init__.py +17 -0
  38. aiofox/http/request/__init__.py +116 -0
  39. aiofox/http/request/form.py +22 -0
  40. aiofox/http/request/json.py +22 -0
  41. aiofox/http/response/__init__.py +170 -0
  42. aiofox/http/response/text.py +221 -0
  43. aiofox/inject.py +234 -0
  44. aiofox/item.py +129 -0
  45. aiofox/libs/__init__.py +0 -0
  46. aiofox/libs/downloadermiddlewares/__init__.py +0 -0
  47. aiofox/libs/downloadermiddlewares/_utils.py +56 -0
  48. aiofox/libs/downloadermiddlewares/cookies.py +186 -0
  49. aiofox/libs/downloadermiddlewares/debug.py +67 -0
  50. aiofox/libs/downloadermiddlewares/defaultheaders.py +42 -0
  51. aiofox/libs/downloadermiddlewares/httperror.py +50 -0
  52. aiofox/libs/downloadermiddlewares/hybridrouting.py +111 -0
  53. aiofox/libs/downloadermiddlewares/redirect.py +123 -0
  54. aiofox/libs/downloadermiddlewares/retry.py +185 -0
  55. aiofox/libs/downloadermiddlewares/snapshot.py +108 -0
  56. aiofox/libs/downloadermiddlewares/stats.py +82 -0
  57. aiofox/libs/downloadermiddlewares/useragent.py +44 -0
  58. aiofox/libs/extensions/__init__.py +1 -0
  59. aiofox/libs/extensions/corestats.py +53 -0
  60. aiofox/libs/extensions/feedexport.py +188 -0
  61. aiofox/libs/extensions/logstats.py +66 -0
  62. aiofox/libs/httpcache/__init__.py +19 -0
  63. aiofox/libs/httpcache/middleware.py +91 -0
  64. aiofox/libs/httpcache/policy.py +69 -0
  65. aiofox/libs/httpcache/storage.py +78 -0
  66. aiofox/libs/job.py +73 -0
  67. aiofox/libs/pipelines/__init__.py +12 -0
  68. aiofox/libs/pipelines/files.py +271 -0
  69. aiofox/libs/pipelines/images.py +126 -0
  70. aiofox/libs/statscollectors.py +93 -0
  71. aiofox/logformatter.py +117 -0
  72. aiofox/middleware/__init__.py +10 -0
  73. aiofox/middleware/adaptive_concurrency.py +107 -0
  74. aiofox/middleware/downloader.py +80 -0
  75. aiofox/middleware/extension.py +18 -0
  76. aiofox/middleware/itempipeline.py +29 -0
  77. aiofox/middleware/manager.py +122 -0
  78. aiofox/py.typed +0 -0
  79. aiofox/queue/__init__.py +64 -0
  80. aiofox/queue/compat.py +61 -0
  81. aiofox/queue/convert.py +123 -0
  82. aiofox/queue/memory/__init__.py +9 -0
  83. aiofox/queue/memory/_queue.py +58 -0
  84. aiofox/queue/rabbitmq/__init__.py +9 -0
  85. aiofox/queue/rabbitmq/_queue.py +116 -0
  86. aiofox/queue/redis/__init__.py +13 -0
  87. aiofox/queue/redis/_queue.py +79 -0
  88. aiofox/queue/redis/_queue_async.py +296 -0
  89. aiofox/settings/__init__.py +490 -0
  90. aiofox/settings/default_settings.py +224 -0
  91. aiofox/signalmanager.py +75 -0
  92. aiofox/signals.py +33 -0
  93. aiofox/spider.py +85 -0
  94. aiofox/templates/project/__init__.py +0 -0
  95. aiofox/templates/project/aiofox.cfg +9 -0
  96. aiofox/templates/project/middlewares.py.tmpl +43 -0
  97. aiofox/templates/project/pipelines.py.tmpl +4 -0
  98. aiofox/templates/project/settings.py.tmpl +119 -0
  99. aiofox/templates/project/spiders/__init__.py +4 -0
  100. aiofox/templates/project/start.py.tmpl +24 -0
  101. aiofox/templates/spiders/basic.tmpl +17 -0
  102. aiofox/templates/spiders/crawl.tmpl +34 -0
  103. aiofox/utils/__init__.py +1 -0
  104. aiofox/utils/common.py +103 -0
  105. aiofox/utils/curl.py +134 -0
  106. aiofox/utils/headers.py +112 -0
  107. aiofox/utils/log.py +222 -0
  108. aiofox/utils/ossignal.py +28 -0
  109. aiofox/utils/othtypes.py +135 -0
  110. aiofox/utils/signal.py +63 -0
  111. aiofox/utils/template.py +38 -0
  112. aiofox/utils/tools.py +325 -0
  113. aiofox-0.2.0.dist-info/METADATA +445 -0
  114. aiofox-0.2.0.dist-info/RECORD +118 -0
  115. aiofox-0.2.0.dist-info/WHEEL +5 -0
  116. aiofox-0.2.0.dist-info/entry_points.txt +2 -0
  117. aiofox-0.2.0.dist-info/licenses/LICENSE +22 -0
  118. aiofox-0.2.0.dist-info/top_level.txt +1 -0
aiofox/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.2.0
aiofox/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ import pkgutil
4
+
5
+ from aiofox.inject import call_grace_instance
6
+
7
+ __version__ = (pkgutil.get_data(__package__, "VERSION") or b"").decode("ascii").strip()
8
+
9
+ __all__ = [
10
+ '__version__',
11
+ 'call_grace_instance'
12
+ ]
aiofox/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ from aiofox.cmdline import execute
4
+
5
+
6
+ if __name__ == '__main__':
7
+ execute()
aiofox/cmdline.py ADDED
@@ -0,0 +1,178 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import os
5
+ import argparse
6
+ import cProfile
7
+ import inspect
8
+ from importlib.metadata import entry_points
9
+ from typing import TYPE_CHECKING, Any, cast
10
+
11
+ import aiofox
12
+ from aiofox.inject import walk_modules
13
+ from aiofox.commands import AiofoxCommand, AiofoxHelpFormatter, BaseRunSpiderCommand
14
+ from aiofox.exceptions import UsageError
15
+ from aiofox.utils.tools import get_project_settings
16
+ from aiofox.utils.common import inside_project
17
+ from aiofox import call_grace_instance
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Callable, Iterator
21
+ from typing import NoReturn
22
+ from aiofox.settings import Settings
23
+
24
+
25
+ def _iter_command_classes(module_name: str) -> Iterator[type[AiofoxCommand]]:
26
+ # TODO: add `name` attribute to commands and and merge this function with
27
+ for module in walk_modules(module_name):
28
+ for obj in vars(module).values():
29
+ if (
30
+ inspect.isclass(obj)
31
+ and issubclass(obj, AiofoxCommand)
32
+ and obj.__module__ == module.__name__
33
+ and obj not in (AiofoxCommand, BaseRunSpiderCommand)
34
+ ):
35
+ yield obj
36
+
37
+
38
+ def _get_commands_from_module(module: str, inproject: bool) -> dict[str, AiofoxCommand]:
39
+ d = {}
40
+ for cmd in _iter_command_classes(module):
41
+ if inproject or not cmd.requires_project:
42
+ cmdname = cmd.__module__.split('.')[-1]
43
+ d[cmdname] = cmd()
44
+ return d
45
+
46
+
47
+ def _get_commands_from_entry_points(inproject: bool, group: str = 'aiofox.commands') -> dict[str, AiofoxCommand]:
48
+ cmds: dict[str, AiofoxCommand] = {}
49
+ for entry_point in entry_points(group=group):
50
+ obj = entry_point.load()
51
+ if inspect.isclass(obj):
52
+ cmds[entry_point.name] = cast(AiofoxCommand, obj())
53
+ else:
54
+ raise Exception(f"Invalid entry point {entry_point.name}")
55
+ return cmds
56
+
57
+
58
+ def _get_commands_dict(settings: Settings, inproject: bool) -> dict[str, AiofoxCommand]:
59
+ cmds = _get_commands_from_module('aiofox.commands', inproject)
60
+ cmds.update(_get_commands_from_entry_points(inproject))
61
+ cmds_module = settings['COMMANDS_MODULE']
62
+ if cmds_module:
63
+ cmds.update(_get_commands_from_module(cmds_module, inproject))
64
+ return cmds
65
+
66
+
67
+ def _pop_command_name(argv: list[str]) -> str | None:
68
+ i = 0
69
+ for arg in argv[1:]:
70
+ if not arg.startswith('-'):
71
+ del argv[i]
72
+ return arg
73
+ i += 1
74
+ return None
75
+
76
+
77
+ def _print_header(settings: Settings, inproject: bool) -> None:
78
+ version = aiofox.__version__
79
+ if inproject:
80
+ print(f"aiofox {version} - project: {settings['BOT_NAME']}\n")
81
+ else:
82
+ print(f"aiofox {version} - no active project\n")
83
+
84
+
85
+ def _print_commands(settings: Settings, inproject: bool) -> None:
86
+ _print_header(settings, inproject)
87
+ print("Usage:")
88
+ print(" aiofox <command> [options] [args]\n")
89
+ print("Available commands:")
90
+ cmds = _get_commands_dict(settings, inproject)
91
+ for cmdname, cmdclass in sorted(cmds.items()):
92
+ print(f" {cmdname:<13} {cmdclass.short_desc()}")
93
+ if not inproject:
94
+ print()
95
+ print(" [ more ] More commands available when run from project directory")
96
+ print()
97
+ print('Use "aiofox <command> -h" to see more info about a command')
98
+
99
+
100
+ def _print_unknown_command(settings: Settings, cmdname: str, inproject: bool) -> None:
101
+ _print_header(settings, inproject)
102
+ print(f"Unknown command: {cmdname}\n")
103
+ print('Use "aiofox" to see available commands')
104
+
105
+
106
+ def _run_print_help(parser: argparse.ArgumentParser, func: Callable[..., Any], *a: Any, **kw: Any) -> None:
107
+ try:
108
+ func(*a, **kw)
109
+ except UsageError as e:
110
+ if str(e):
111
+ parser.error(str(e))
112
+ if e.print_help:
113
+ parser.print_help()
114
+ sys.exit(2)
115
+
116
+
117
+ def execute(argv: list[str] | None = None, settings: Settings | None = None) -> NoReturn:
118
+ if argv is None:
119
+ argv = sys.argv
120
+
121
+ if settings is None:
122
+ settings = get_project_settings()
123
+ # set EDITOR from environment if available
124
+ try:
125
+ editor = os.environ['EDITOR']
126
+ except KeyError:
127
+ pass
128
+ else:
129
+ settings['EDITOR'] = editor
130
+
131
+ inproject = inside_project()
132
+ cmds = _get_commands_dict(settings, inproject)
133
+ cmdname = _pop_command_name(argv)
134
+ if not cmdname:
135
+ _print_commands(settings, inproject)
136
+ sys.exit(0)
137
+ elif cmdname not in cmds:
138
+ _print_unknown_command(settings, cmdname, inproject)
139
+ sys.exit(2)
140
+
141
+ cmd = cmds[cmdname]
142
+ parser = argparse.ArgumentParser(formatter_class=AiofoxHelpFormatter,
143
+ usage=f"aiofox {cmdname} {cmd.syntax()}",
144
+ conflict_handler='resolve',
145
+ description=cmd.long_desc())
146
+ settings.setdict(cmd.default_settings, priority='command')
147
+ cmd.settings = settings
148
+ cmd.add_options(parser)
149
+ opts, args = parser.parse_known_args(args=argv[1:])
150
+ _run_print_help(parser, cmd.process_options, args, opts)
151
+
152
+ if getattr(cmd, "requires_process"):
153
+ # cmd.crawler_process = CrawlerProcess(settings)
154
+ cmd.crawler_process = call_grace_instance("crawler_process", settings)
155
+ _run_print_help(parser, _run_command, cmd, args, opts)
156
+ sys.exit(cmd.exitcode)
157
+
158
+
159
+ def _run_command(cmd: AiofoxCommand, args: list[str], opts: argparse.Namespace) -> None:
160
+ if opts.profile:
161
+ _run_command_profiled(cmd, args, opts)
162
+ else:
163
+ cmd.run(args, opts)
164
+
165
+
166
+ def _run_command_profiled(cmd: AiofoxCommand, args: list[str], opts: argparse.Namespace) -> None:
167
+ if opts.profile:
168
+ sys.stderr.write(f"aiofox: writing cProfile stats to {opts.profile!r}\n")
169
+ loc = locals()
170
+ p = cProfile.Profile()
171
+ p.runctx('cmd.run(args, opts)', globals(), loc)
172
+ if opts.profile:
173
+ p.dump_stats(opts.profile)
174
+
175
+
176
+ if __name__ == '__main__':
177
+ execute()
178
+
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import argparse
5
+ from collections.abc import Iterable
6
+ from typing import Any, Dict, TYPE_CHECKING
7
+
8
+
9
+ from aiofox.utils.common import arglist_to_dict
10
+ from aiofox.exceptions import UsageError
11
+ from aiofox.libs.extensions.feedexport import (
12
+ feed_format_from_file_uri, normalize_feed_format)
13
+
14
+ if TYPE_CHECKING:
15
+ from aiofox.crawler import Crawler
16
+ from aiofox.settings import Settings
17
+
18
+
19
+ class AiofoxCommand:
20
+
21
+ requires_project = False
22
+ crawler_process: Any = None
23
+ requires_process = True
24
+
25
+ # default settings to be used for this command instead of global defaults
26
+ default_settings: Dict[str, Any] = {}
27
+
28
+ exitcode = 0
29
+
30
+ def __init__(self) -> None:
31
+ self.settings: Any = None # set in aiofox.cmdline
32
+
33
+ def set_crawler(self, crawler: Crawler) -> None:
34
+ if hasattr(self, '_crawler'):
35
+ raise RuntimeError("crawler already set")
36
+ self._crawler = crawler
37
+
38
+ def syntax(self) -> str:
39
+ """
40
+ Command syntax (preferably one-line). Do not include command name.
41
+ """
42
+ return ""
43
+
44
+ def short_desc(self) -> str:
45
+ """
46
+ A short description of the command
47
+ """
48
+ return ""
49
+
50
+ def long_desc(self) -> str:
51
+ """A long description of the command. Return short description when not
52
+ available. It cannot contain newlines since contents will be formatted
53
+ by optparser which removes newlines and wraps text.
54
+ """
55
+ return self.short_desc()
56
+
57
+ def help(self) -> str:
58
+ """An extensive help for the command. It will be shown when using the
59
+ "help" command. It can contain newlines since no post-formatting will
60
+ be applied to its contents.
61
+ """
62
+ return self.long_desc()
63
+
64
+ def add_options(self, parser: argparse.ArgumentParser) -> None:
65
+ """
66
+ Populate option parse with options available for this command
67
+ """
68
+ group = parser.add_argument_group(title='Global Options')
69
+ group.add_argument("--logfile", metavar="FILE",
70
+ help="also write logs to FILE")
71
+ group.add_argument("-L", "--loglevel", metavar="LEVEL", default=None,
72
+ help=f"log level (default: {self.settings['LOG_LEVEL']})")
73
+ group.add_argument("--nolog", action="store_true",
74
+ help="disable logging completely")
75
+ group.add_argument("--profile", metavar="FILE", default=None,
76
+ help="write python cProfile stats to FILE")
77
+ group.add_argument("--pidfile", metavar="FILE",
78
+ help="write process ID to FILE")
79
+ group.add_argument("-s", "--set", action="append", default=[], metavar="NAME=VALUE",
80
+ help="set/override setting (may be repeated)")
81
+
82
+ def process_options(self, args: list[str], opts: argparse.Namespace) -> None:
83
+ try:
84
+ self.settings.setdict(arglist_to_dict(opts.set),
85
+ priority='cmdline')
86
+ except ValueError:
87
+ raise UsageError("Invalid -s value, use -s NAME=VALUE", print_help=False)
88
+
89
+ if opts.logfile:
90
+ self.settings.set('LOG_ENABLED', True, priority='cmdline')
91
+ self.settings.set('LOG_FILE', True, priority='cmdline')
92
+ self.settings.set('LOG_FILENAME', opts.logfile, priority='cmdline')
93
+
94
+ if opts.loglevel:
95
+ self.settings.set('LOG_ENABLED', True, priority='cmdline')
96
+ self.settings.set('LOG_LEVEL', opts.loglevel, priority='cmdline')
97
+
98
+ if opts.nolog:
99
+ self.settings.set('LOG_ENABLED', False, priority='cmdline')
100
+
101
+ if opts.pidfile:
102
+ with open(opts.pidfile, "w") as f:
103
+ f.write(str(os.getpid()) + os.linesep)
104
+
105
+ def run(self, args: list[str], opts: argparse.Namespace) -> None:
106
+ """
107
+ Entry point for running commands
108
+ """
109
+ raise NotImplementedError
110
+
111
+
112
+ class BaseRunSpiderCommand(AiofoxCommand):
113
+ """
114
+ Common class used to share functionality between the crawl, parse and runspider commands
115
+ """
116
+ def add_options(self, parser: argparse.ArgumentParser) -> None:
117
+ AiofoxCommand.add_options(self, parser)
118
+ parser.add_argument("-a", dest="spargs", action="append", default=[], metavar="NAME=VALUE",
119
+ help="set spider argument (may be repeated)")
120
+ parser.add_argument("-o", "--output", metavar="FILE", action="append",
121
+ help="append scraped items to the end of FILE (use - for stdout)")
122
+ parser.add_argument("-O", "--overwrite-output", metavar="FILE", action="append",
123
+ help="dump scraped items into FILE, overwriting any existing file")
124
+ parser.add_argument("-t", "--output-format", metavar="FORMAT",
125
+ help="format to use for dumping items")
126
+
127
+ def process_options(self, args: list[str], opts: argparse.Namespace) -> None:
128
+ AiofoxCommand.process_options(self, args, opts)
129
+ try:
130
+ opts.spargs = arglist_to_dict(opts.spargs)
131
+ except ValueError:
132
+ raise UsageError("Invalid -a value, use -a NAME=VALUE", print_help=False)
133
+ self._update_feeds(opts, self.settings)
134
+
135
+ def _update_feeds(self, opts: argparse.Namespace, settings: Settings) -> None:
136
+ """Turn -o / -O / -t into FEEDS entries, merged with the feeds already configured."""
137
+ # tuples, not lists: the `aiofox.commands.list` submodule is bound to the name `list`
138
+ # of this package once it is imported, which hides the built-in of the same name
139
+ outputs = tuple(getattr(opts, 'output', None) or ())
140
+ overwrites = tuple(getattr(opts, 'overwrite_output', None) or ())
141
+ output_format = getattr(opts, 'output_format', None)
142
+
143
+ if output_format and not (outputs or overwrites):
144
+ raise UsageError('Cannot use -t/--output-format without -o or -O.')
145
+ if output_format:
146
+ output_format = normalize_feed_format(output_format)
147
+ if len(set(outputs + overwrites)) != len(outputs + overwrites):
148
+ raise UsageError('No duplicate output/overwrite values are allowed.')
149
+ files = outputs + overwrites
150
+ if '-' in files and len(files) > 1:
151
+ raise UsageError('Only one output can be set to stdout ("-").')
152
+
153
+ feeds = settings.getdict('FEEDS')
154
+ for fname, overwrite in ([(o, False) for o in outputs]
155
+ + [(o, True) for o in overwrites]):
156
+ feed_format = output_format
157
+ if not feed_format:
158
+ if fname == '-':
159
+ raise UsageError(
160
+ 'The output format must be given with -t when writing to stdout ("-").')
161
+ feed_format = feed_format_from_file_uri(fname)
162
+ if not feed_format:
163
+ raise UsageError(
164
+ f"Unrecognized output format for '{fname}'; specify it with -t/--output-format.")
165
+ feeds[fname] = {**feeds.get(fname, {}), 'format': feed_format, 'overwrite': overwrite}
166
+ settings.set('FEEDS', feeds, priority='cmdline')
167
+
168
+
169
+ class AiofoxHelpFormatter(argparse.HelpFormatter):
170
+ """
171
+ Help Formatter for aiofox command line help messages.
172
+ """
173
+ def __init__(self, prog: str, indent_increment: int = 2,
174
+ max_help_position: int = 24, width: int | None = None) -> None:
175
+ super().__init__(prog, indent_increment=indent_increment,
176
+ max_help_position=max_help_position, width=width)
177
+
178
+ def _join_parts(self, part_strings: Iterable[str]) -> str:
179
+ # a copy of the sequence, it gets the titles and underlines inserted; not written
180
+ # `list(...)`: once the commands were loaded, the name `list` of this module is
181
+ # the `aiofox.commands.list` submodule
182
+ parts = self.format_part_strings([*part_strings])
183
+ return super()._join_parts(parts)
184
+
185
+ def format_part_strings(self, part_strings: list[str]) -> list[str]:
186
+ """
187
+ Underline and title case command line help message headers.
188
+ """
189
+ if part_strings and part_strings[0].startswith("usage: "):
190
+ part_strings[0] = "Usage\n=====\n " + part_strings[0][len('usage: '):]
191
+ headings = [i for i in range(len(part_strings)) if part_strings[i].endswith(':\n')]
192
+ for index in headings[::-1]:
193
+ char = '-' if "Global Options" in part_strings[index] else '='
194
+ part_strings[index] = part_strings[index][:-2].title()
195
+ underline = ''.join(["\n", (char * len(part_strings[index])), "\n"])
196
+ part_strings.insert(index + 1, underline)
197
+ return part_strings
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from aiofox.commands import BaseRunSpiderCommand
6
+ from aiofox.exceptions import UsageError
7
+
8
+ if TYPE_CHECKING:
9
+ import argparse
10
+
11
+
12
+ class Command(BaseRunSpiderCommand):
13
+
14
+ requires_project = True
15
+
16
+ def syntax(self) -> str:
17
+ return "[options] <spider>"
18
+
19
+ def short_desc(self) -> str:
20
+ return "Run a spider"
21
+
22
+ def run(self, args: list[str], opts: argparse.Namespace) -> None:
23
+ if len(args) < 1:
24
+ raise UsageError()
25
+ elif len(args) > 1:
26
+ raise UsageError("running 'aiofox crawl' with more than one spider is not supported")
27
+ spname = args[0]
28
+
29
+ crawl_defer = self.crawler_process.crawl(spname, **opts.spargs)
30
+
31
+ if getattr(crawl_defer, 'result', None) is not None and issubclass(crawl_defer.result.type, Exception):
32
+ self.exitcode = 1
33
+ else:
34
+ self.crawler_process.start()
35
+
36
+ if (
37
+ self.crawler_process.bootstrap_failed
38
+ or hasattr(self.crawler_process, 'has_exception') and self.crawler_process.has_exception
39
+ ):
40
+ self.exitcode = 1
@@ -0,0 +1,174 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import string
6
+
7
+ from importlib import import_module
8
+ from os.path import join, dirname, abspath, exists, splitext
9
+ from typing import TYPE_CHECKING, cast
10
+ from urllib.parse import urlparse
11
+
12
+ import aiofox
13
+ from aiofox.commands import AiofoxCommand
14
+ from aiofox.utils.template import render_templatefile, string_camelcase
15
+ from aiofox.exceptions import UsageError
16
+
17
+ if TYPE_CHECKING:
18
+ import argparse
19
+
20
+ # where a generated spider starts when no domain is given on the command line
21
+ DEFAULT_START_URL = 'https://example.com/'
22
+
23
+
24
+ def sanitize_module_name(module_name: str) -> str:
25
+ """Sanitize the given module name, by replacing dashes and points
26
+ with underscores and prefixing it with a letter if it doesn't start
27
+ with one
28
+ """
29
+ module_name = module_name.replace('-', '_').replace('.', '_')
30
+ if module_name[0] not in string.ascii_letters:
31
+ module_name = "a" + module_name
32
+ return module_name
33
+
34
+
35
+ def start_url(target: str) -> str:
36
+ """The URL a generated spider starts from, for the *target* given on the
37
+ command line: a domain (``https://`` is assumed, and a bare domain gets
38
+ its root path) or a full URL.
39
+ """
40
+ target = target.strip()
41
+ if '://' not in target:
42
+ target = f'https://{target}'
43
+ if not urlparse(target).path:
44
+ target += '/'
45
+ return target
46
+
47
+
48
+ class Command(AiofoxCommand):
49
+
50
+ requires_project = False
51
+ default_settings = {'LOG_ENABLED': False}
52
+ requires_process = False
53
+
54
+ def syntax(self) -> str:
55
+ return "[options] <name> [domain]"
56
+
57
+ def short_desc(self) -> str:
58
+ return "Generate new spider in project using pre-defined templates"
59
+
60
+ def long_desc(self) -> str:
61
+ return ("Generate a new spider in the current project from a template. The optional "
62
+ "domain is where the spider starts, e.g. `aiofox genspider quotes "
63
+ "quotes.toscrape.com` gives start_urls = ['https://quotes.toscrape.com/']; "
64
+ f"without it the spider starts at {DEFAULT_START_URL}.")
65
+
66
+ def add_options(self, parser: argparse.ArgumentParser) -> None:
67
+ AiofoxCommand.add_options(self, parser)
68
+ parser.add_argument("-l", "--list", dest="list", action="store_true",
69
+ help="List available templates")
70
+ parser.add_argument("-d", "--dump", dest="dump", metavar="TEMPLATE",
71
+ help="Dump template to standard output")
72
+ parser.add_argument("-t", "--template", dest="template", default="basic",
73
+ help="Uses a custom template.")
74
+ parser.add_argument("--force", dest="force", action="store_true",
75
+ help="If the spider already exists, overwrite it with the template")
76
+
77
+ def run(self, args: list[str], opts: argparse.Namespace) -> None:
78
+ if opts.list:
79
+ self._list_templates()
80
+ return
81
+ if opts.dump:
82
+ template_file = self._find_template(opts.dump)
83
+ if template_file:
84
+ with open(template_file, "r") as f:
85
+ print(f.read())
86
+ return
87
+ if not args:
88
+ raise UsageError()
89
+ if len(args) > 2:
90
+ raise UsageError("aiofox genspider takes a spider name and, optionally, the domain "
91
+ "it should start from", print_help=False)
92
+
93
+ name = args[0]
94
+ module = sanitize_module_name(name)
95
+
96
+ if self.settings.get('BOT_NAME') == module:
97
+ print("Cannot create a spider with the same name as your project")
98
+ return
99
+
100
+ if not opts.force and self._spider_exists(name):
101
+ return
102
+
103
+ template_file = self._find_template(opts.template)
104
+ if template_file:
105
+ url = start_url(args[1]) if len(args) > 1 else DEFAULT_START_URL
106
+ self._genspider(module, name, opts.template, template_file, url)
107
+
108
+ def _genspider(self, module: str, name: str, template_name: str, template_file: str,
109
+ url: str) -> None:
110
+ """Generate the spider module, based on the given template"""
111
+ capitalized_module = ''.join(s.capitalize() for s in module.split('_'))
112
+ tvars = {
113
+ 'project_name': self.settings.get('BOT_NAME'),
114
+ 'ProjectName': string_camelcase(self.settings.get('BOT_NAME')),
115
+ 'module': module,
116
+ 'name': name,
117
+ 'classname': f'{capitalized_module}Spider',
118
+ 'url': url,
119
+ }
120
+ if self.settings.get('NEWSPIDER_MODULE'):
121
+ spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])
122
+ # an imported (non-namespace) module always has __file__ set; the
123
+ # cast is a runtime no-op and keeps the same TypeError if it were None
124
+ spiders_dir = abspath(dirname(cast(str, spiders_module.__file__)))
125
+ else:
126
+ spiders_module = None
127
+ spiders_dir = "."
128
+ spider_file = f"{join(spiders_dir, module)}.py"
129
+ shutil.copyfile(template_file, spider_file)
130
+ render_templatefile(spider_file, **tvars)
131
+ print(f"Created spider {name!r} using template {template_name!r} ",
132
+ end=('' if spiders_module else '\n'))
133
+ if spiders_module:
134
+ print(f"in module:\n {spiders_module.__name__}.{module}")
135
+
136
+ def _find_template(self, template: str) -> str | None:
137
+ template_file = join(self.templates_dir, f'{template}.tmpl')
138
+ if exists(template_file):
139
+ return template_file
140
+ print(f"Unable to find template: {template}\n")
141
+ print('Use "aiofox genspider --list" to see all available templates.')
142
+ return None
143
+
144
+ def _list_templates(self) -> None:
145
+ print("Available templates:")
146
+ for filename in sorted(os.listdir(self.templates_dir)):
147
+ if filename.endswith('.tmpl'):
148
+ print(f" {splitext(filename)[0]}")
149
+
150
+ def _spider_exists(self, name: str) -> bool:
151
+ if not self.settings.get('NEWSPIDER_MODULE'):
152
+ # if run as a standalone command and file with same filename already exists
153
+ if exists(name + ".py"):
154
+ print(f"{abspath(name + '.py')} already exists")
155
+ return True
156
+ return False
157
+
158
+ # a file with the same name exists in the target directory
159
+ spiders_module = import_module(self.settings['NEWSPIDER_MODULE'])
160
+ # see the comment in _genspider: __file__ is always set on an imported module
161
+ spiders_dir = dirname(cast(str, spiders_module.__file__))
162
+ spiders_dir_abs = abspath(spiders_dir)
163
+ if exists(join(spiders_dir_abs, name + ".py")):
164
+ print(f"{join(spiders_dir_abs, (name + '.py'))} already exists")
165
+ return True
166
+
167
+ return False
168
+
169
+ @property
170
+ def templates_dir(self) -> str:
171
+ return join(
172
+ self.settings['TEMPLATES_DIR'] or join(aiofox.__path__[0], 'templates'),
173
+ 'spiders'
174
+ )
@@ -0,0 +1,34 @@
1
+ """``aiofox list``: the spiders a project defines (inside a project only)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from aiofox.commands import AiofoxCommand
7
+ from aiofox.exceptions import UsageError
8
+ from aiofox.inject import DependencyInjection
9
+
10
+
11
+ class Command(AiofoxCommand):
12
+
13
+ requires_project = True
14
+ requires_process = False
15
+
16
+ def syntax(self) -> str:
17
+ return "[options]"
18
+
19
+ def short_desc(self) -> str:
20
+ return "List the spiders of the project"
21
+
22
+ def long_desc(self) -> str:
23
+ return "Print the name of every spider the project defines, one per line, sorted."
24
+
25
+ def run(self, args: list[str], opts: Any) -> None:
26
+ if args:
27
+ raise UsageError("The list command takes no argument")
28
+ assert self.settings is not None
29
+ module = self.settings.get('NEWSPIDER_MODULE')
30
+ if not module:
31
+ raise UsageError("No active project: run this command from a project directory")
32
+ spiders = DependencyInjection.load_all_spider('./' + module)
33
+ for name in sorted(spiders):
34
+ print(name)
aiofox/commands/new.py ADDED
@@ -0,0 +1,9 @@
1
+ from __future__ import annotations
2
+
3
+ from aiofox.commands.startproject import Command as StartProjectCommand
4
+
5
+
6
+ class Command(StartProjectCommand):
7
+
8
+ def short_desc(self) -> str:
9
+ return "Create new project (shortcut for startproject)"