Skip to content
This repository was archived by the owner on Jun 20, 2024. It is now read-only.

Commit 608d032

Browse files
author
Ari Archer
committed
1.2.0 : support for context managers, better API
Signed-off-by: Ari Archer <[email protected]>
1 parent 7e7c7a7 commit 608d032

File tree

6 files changed

+98
-25
lines changed

6 files changed

+98
-25
lines changed

awc/__init__.py

+17-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from . import const, exc, util
1313

14-
__version__: typing.Final[str] = "1.1.0"
14+
__version__: typing.Final[str] = "1.2.0"
1515

1616

1717
class Awc:
@@ -54,14 +54,16 @@ def api_key(self, value: typing.Optional[str]) -> None:
5454
raise
5555
awc.exc.InvalidAPIKeyError -- on invalid API key"""
5656

57+
self.__api_key = value
58+
5759
if value is not None and self.get(api="amiadmin").text != "1":
60+
self.__api_key = None
61+
5862
raise exc.InvalidAPIKeyError(
5963
f"{value[:5]}{'*' * (len(value) - 5)}"[:50]
6064
+ (" ..." if len(value) > 50 else "")
6165
)
6266

63-
self.__api_key = value
64-
6567
@property
6668
def rate_limit_wait(self) -> typing.Union[int, float]:
6769
"""rate limit wait time getter -- get the rate limit wait in seconds
@@ -126,6 +128,12 @@ def __getitem__(self, path: str) -> str:
126128
return str -- the URL"""
127129
return self.instance.join(path).url # type: ignore
128130

131+
def __enter__(self) -> "Awc":
132+
return self
133+
134+
def __exit__(self, *_: typing.Any) -> None:
135+
self.end()
136+
129137
def request(
130138
self,
131139
method: typing.Callable[..., requests.Response],
@@ -187,6 +195,12 @@ def post(self, *args: typing.Any, **kwargs: typing.Any) -> requests.Response:
187195
"""similar to `Awc.request` but for POST requests"""
188196
return self.request(self.session.post, *args, **kwargs)
189197

198+
def end(self) -> None:
199+
"""end an instance ( close it )"""
200+
201+
self.__api_key = None
202+
self.session.close()
203+
190204
@staticmethod
191205
def require_key(
192206
f: typing.Callable[..., typing.Any]

awc/api.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,9 @@ def sql(
111111
raise
112112
awc.exc.UnexpectedResponseError from requests.exceptions.InvalidJSONError --
113113
on invalid JSON
114-
"""
114+
ValueError -- on invalid queries
115+
116+
return typing.List[typing.List[typing.Any]] -- query results"""
115117

116118
data: typing.Dict[str, typing.Union[typing.Iterable[str], str]] = {"sql": queries}
117119

@@ -155,19 +157,19 @@ def get_comment_lock(awc: Awc) -> bool:
155157
"""gets comments lock status
156158
157159
awc: awc.Awc -- the awc.Awc instance to work on"""
158-
return awc.get(api="lock").text == "1"
160+
return util.resp_to_bool(awc.get(api="lock").text)
159161

160162

161163
@Awc.require_key
162164
def toggle_comment_lock(awc: Awc) -> bool:
163165
"""toggles comments lock status
164166
165167
awc: awc.Awc -- the awc.Awc instance to work on"""
166-
return awc.post(api="lock").text == "1"
168+
return util.resp_to_bool(awc.post(api="lock").text)
167169

168170

169171
def amiadmin(awc: Awc) -> bool:
170172
"""returns your admin status ( `True` if API key is correct ( you are admin ) )
171173
172174
awc: awc.Awc -- the awc.Awc instance to work on"""
173-
return awc.get(api="amiadmin").text == "1"
175+
return util.resp_to_bool(awc.get(api="amiadmin").text)

awc/sql/__init__.py

+27
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,33 @@ def all(cls) -> pypika.queries.QueryBuilder:
6767
return pypika.queries.QueryBuilder -- `SELECT * FROM self.t` query"""
6868
return pypika.Query.from_(cls.t).select("*") # type: ignore
6969

70+
@classmethod
71+
def set(
72+
cls,
73+
where: pypika.queries.QueryBuilder,
74+
what: typing.Dict[pypika.Column, typing.Any],
75+
) -> pypika.queries.QueryBuilder:
76+
"""SET statement
77+
78+
where: pypika.queries.QueryBuilder -- the condition on which to set
79+
what: dict[pypika.Column, typing.Any] -- the columns and values to set
80+
81+
return pypika.queries.QueryBuilder -- the query"""
82+
q: pypika.queries.QueryBuilder = cls.t.update()
83+
84+
for k, v in what.items():
85+
q = q.set(k, v) # type: ignore
86+
87+
return q.where(where) # type: ignore
88+
89+
@classmethod
90+
def purge(cls) -> pypika.queries.QueryBuilder:
91+
"""purge the table ( delete everything ) **BE CAREFUL**
92+
93+
return pypika.queries.QueryBuilder -- the query"""
94+
95+
return pypika.Query.from_(cls.t).delete() # type: ignore
96+
7097

7198
class Comment(SQLTable):
7299
"""comment / post table"""

awc/sql/helpers.py

+19-17
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ def unwhitelist(author: str) -> typing.List[pypika.queries.QueryBuilder]:
4848
]
4949

5050

51+
def ban_ip(ip: pypika.queries.QueryBuilder) -> typing.List[pypika.queries.QueryBuilder]:
52+
"""ban an ip
53+
54+
ip: pypika.queries.QueryBuilder -- the query to get the user ip
55+
56+
return typing.List[pypika.queries.QueryBuilder] -- the queries"""
57+
58+
return [Ban.add(ip)] # type: ignore
59+
60+
5161
def ban(author: str) -> typing.List[pypika.queries.QueryBuilder]:
5262
"""ban and unwhitelist a user
5363
@@ -58,14 +68,14 @@ def ban(author: str) -> typing.List[pypika.queries.QueryBuilder]:
5868
author = util.truncate(author, const.MAX_AUTHOR_LEN)
5969

6070
return [
61-
Ban.add(IpWhitelist.select(IpWhitelist.author == author, "ip")) # type: ignore
71+
*ban_ip(IpWhitelist.select(IpWhitelist.author == author, "ip")) # type: ignore
6272
] + unwhitelist(author)
6373

6474

6575
def unban(ip: str) -> typing.List[pypika.queries.QueryBuilder]:
6676
"""unban an IP
6777
68-
ip: str -- the SHA256 hash of the IP bein unbannned
78+
ip: str -- the SHA256 hash of the IP being unbannned
6979
7080
return typing.List[pypika.queries.QueryBuilder] -- the queries"""
7181
return [delete(Ban.query(Ban.ip == ip).limit(1))] # type: ignore
@@ -82,19 +92,11 @@ def censor_comments(
8292
8393
return typing.List[pypika.queries.QueryBuilder] -- the queries"""
8494
return [
85-
Comment.t.update() # type: ignore
86-
.set(Comment.author, censoring)
87-
.set(Comment.content, censoring)
88-
.where(where)
95+
Comment.set(
96+
where,
97+
{
98+
Comment.author: censoring,
99+
Comment.content: censoring,
100+
},
101+
)
89102
]
90-
91-
92-
def set_comments_admin(
93-
where: pypika.queries.QueryBuilder,
94-
value: bool = True,
95-
) -> typing.List[pypika.queries.QueryBuilder]:
96-
"""set admin status on comments
97-
98-
where: pypika.queries.QueryBuilder -- the condition on which to set
99-
value: bool = True -- the value to set the admin status to"""
100-
return [Comment.t.update().set(Comment.admin, value).where(where)] # type: ignore

awc/util.py

+10
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,13 @@ def truncate(content: str, length: int, do_warn: bool = True) -> str:
4545
warn(ContentTruncatedWarning(content, length))
4646

4747
return content[:length]
48+
49+
50+
def resp_to_bool(resp: str) -> bool:
51+
"""convets a response like 0 and 1 to boolean
52+
53+
resp: str -- the response
54+
55+
return bool -- the converted boolean"""
56+
57+
return resp == "1"

examples/main.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
from warnings import filterwarnings as filter_warnings
77

88
import awc
9-
import awc.const
109
import awc.api
10+
import awc.const
1111
import awc.exc
1212
import awc.sql # tip : use pypika as this library is very compatible with it :)
1313
import awc.sql.helpers
@@ -116,6 +116,21 @@ def main() -> int:
116116

117117
print("you are", "an" if awc.api.amiadmin(api) else "not an", "admin")
118118

119+
print(f"ill call you {__name__!r} now")
120+
print(
121+
awc.api.sql(
122+
api,
123+
awc.sql.sql(
124+
awc.sql.IpWhitelist.set(
125+
awc.sql.IpWhitelist.author == author, # type: ignore
126+
{awc.sql.IpWhitelist.author: __name__},
127+
)
128+
),
129+
)
130+
)
131+
132+
print("whoami api returned", (author := awc.api.whoami(api)))
133+
119134
print("imma ban you wait")
120135
print(awc.api.sql(api, awc.sql.multisql(awc.sql.helpers.ban(author))))
121136

@@ -126,6 +141,9 @@ def main() -> int:
126141
print("lol okok wait, ill unban you :) ( i wont whitelist you bc i said so !! )")
127142
print(awc.api.sql(api, awc.sql.multisql(awc.sql.helpers.unban(author))))
128143

144+
# close the connection and stuff
145+
api.end() # note : you can also use a `with` context manager
146+
129147
return 0
130148

131149

0 commit comments

Comments
 (0)