本页还没有译文
本页 58 段还没译成日本語,下面显示的是英文原文。Durable Object Base Class
还没翻译译自英文(developers.cloudflare.com)本页 58 段都还没译
The DurableObject base class is an abstract class which all Durable Objects inherit from. This base class provides a set of optional methods, frequently referred to as handler methods, which can respond to events, for example a webSocketMessage when using the WebSocket Hibernation API. To provide a concrete example, here is a Durable Object MyDurableObject which extends DurableObject and implements the fetch handler to return "Hello, World!" to the calling Worker.
Python
from workers import DurableObject, Response
class MyDurableObject(DurableObject):
def __init__(self, ctx, env):
super().__init__(ctx, env)
async def fetch(self, request):
return Response("Hello, World!")Methods
fetch
fetch(request Request): Response | Promise<Response>- Takes an HTTP Request and returns an HTTP Response. This method allows the Durable Object to emulate an HTTP server where a Worker with a binding to that object is the client. - This method can beasync.- Durable Objects support RPC calls as of compatibility date 2024-04-03. RPC methods are preferred over
fetch()when your application does not follow HTTP request/response flow.
- Durable Objects support RPC calls as of compatibility date 2024-04-03. RPC methods are preferred over
Parameters
requestRequest - the incoming HTTP request object.
Return values
- A Response or Promise<Response>.
Example
Python
from workers import DurableObject, Response
from urllib.parse import urlparse
class MyDurableObject(DurableObject):
async def fetch(self, request):
path = urlparse(request.url).path
if path == "/hello":
return Response("Hello, World!")
return Response("Not found", status=404)alarm
alarm(alarmInfo? AlarmInvocationInfo): void | Promise<void>- Called by the system when a scheduled alarm time is reached.
- The
alarm()handler has guaranteed at-least-once execution and will be retried upon failure using exponential backoff, starting at two second delays for up to six retries. Retries will be performed if the method fails with an uncaught exception. - This method can be
async. - Refer to Alarms for more information.
Parameters
alarmInfoAlarmInvocationInfo (optional) - an object containing retry information:retryCountnumber - the number of times this alarm event has been retried.isRetryboolean -trueif this alarm event is a retry,falseotherwise.
Return values
- None.
Example
Python
from workers import DurableObject
class MyDurableObject(DurableObject):
async def alarm(self, alarm_info=None):
if alarm_info and alarm_info.isRetry:
print(f"Alarm retry attempt {alarm_info.retryCount}")
await self.process_scheduled_task()webSocketMessage
webSocketMessage(ws WebSocket, message string | ArrayBuffer): void | Promise<void>- Called by the system when an accepted WebSocket receives a message. - This method is not called for WebSocket control frames. The system will respond to an incoming WebSocket protocol ping automatically without interrupting hibernation.- This method can be
async.
- This method can be
Parameters
wsWebSocket - the WebSocket that received the message. Use this reference to send responses or access serialized attachments.messagestring | ArrayBuffer - the message data. Text messages arrive asstring, binary messages asArrayBuffer.
Return values
- None.
Example
Python
from workers import DurableObject
class MyDurableObject(DurableObject):
async def webSocketMessage(self, ws, message):
if isinstance(message, str):
ws.send(f"Received: {message}")
else:
ws.send(f"Received {len(message)} bytes")webSocketClose
webSocketClose(ws WebSocket, code number, reason string, wasClean boolean): void | Promise<void>- Called by the system when a WebSocket connection is closed.- With the
web_socket_auto_reply_to_closecompatibility flag (enabled by default on compatibility dates on or after2026-04-07), the runtime automatically sends a reciprocal Close frame and transitionsreadyStatetoCLOSEDbefore this handler is called. You do not need to callws.close()— but doing so is safe (the call is silently ignored). - On older compatibility dates (before
2026-04-07), you must callws.close(code, reason)inside this handler to complete the WebSocket close handshake. Failing to reciprocate the close will result in1006errors on the client, representing an abnormal closure per the WebSocket specification. - This method can be
async.
- With the
Parameters
wsWebSocket - the WebSocket that was closed.codenumber - the WebSocket close code sent by the peer (e.g.,1000for normal closure,1001for going away).reasonstring - a string indicating why the connection was closed. May be empty.wasCleanboolean -trueif the connection closed cleanly with a proper closing handshake,falseotherwise.
Return values
- None.
Example
Python
from workers import DurableObject
class MyDurableObject(DurableObject):
async def webSocketClose(self, ws, code, reason, was_clean):
ws.close(code, reason)
print(f"WebSocket closed: code={code}, reason={reason}")webSocketError
webSocketError(ws WebSocket, error unknown): void | Promise<void>- Called by the system when a non-disconnection error occurs on a WebSocket connection. - This method can beasync.
Parameters
wsWebSocket - the WebSocket that encountered an error.errorunknown - the error that occurred. May be anErrorobject or another type depending on the error source.
Return values
- None.
Example
Python
from workers import DurableObject
class MyDurableObject(DurableObject):
async def webSocketError(self, ws, error):
print(f"WebSocket error: {error}")Properties
ctx
ctx is a readonly property of type DurableObjectState providing access to storage, WebSocket management, and other instance-specific functionality.
env
env contains the environment bindings available to this Durable Object, as defined in your Wrangler configuration.
Related resources
- Use WebSockets for WebSocket handler best practices.
- Alarms API for scheduling future work.
- RPC methods for type-safe method calls.